Group array of objects inside nested Array and add its total to a new Array

Viewed 74

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 }
2 Answers

Simpler solution I can think of:

const result = {}
arr.forEach(el => {
  el.taxes.forEach(tax => {
    result[tax.name] = (result[tax.name] || 0)+ tax.total
  })
})
const solution = Object.entries(result).map(el => ({name: el[0], total: el[1]}))
console.log(solution)

@Atal Shrivastava, I appreciate your attempt, This is very simple solation, 1st check if entry exist or not, if not create entry else increase entry...

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.reduce((result, { taxes }) => {
    for (const { name, total } of taxes)
        if (result[name])
            result[name] += total
        else
            result[name] = total

    return result;
}, {})

console.log(result);

Related