I have an array of object with different tax rate and its value. I'm trying to combine all values with same tax rate into single object. Below is my code
const arr = [
{
"taxes": [
{
"name": "CGST 2.5%",
"total": 4.01,
},
{
"name": "SGST 2.5%",
"total": 4.01,
},
],
},
{
"taxes": [
{
"name": "CGST 6%",
"total": 10,
},
{
"name": "SGST 6%",
"total": 10,
},
],
},
{
"taxes": [
{
"name": "CGST 2.5%",
"total": 16.42,
},
{
"name": "SGST 2.5%",
"total": 16.42,
},
],
},
{
"taxes": [
{
"name": "CGST 2.5%",
"total": 0,
},
{
"name": "SGST 2.5%",
"total": 0,
},
],
},
{
"taxes": [
{
"name": "CGST 6%",
"total": 12,
},
{
"name": "SGST 6%",
"total": 12,
},
],
},
];
const result = arr.map(item => {
return Object.values(item.taxes.reduce((r, { name, total }) => {
(r[name] || (r[name] = [name, 0]))[1] += total;
return r;
}, {}));
})
console.log(result);
I have searched and got reduce function which is working but I'm not able to make it to work with the nested arrays.
Kindly tolerate with my ability as I'm not at all familiar with the reduce function how it works.
What I wanted it will return me a new Array like
{ "CGST 2.5%": 20.43, "SGST 2.5%": 20.43, "CGST 6%": 22, "SGST 6%": 22 }