Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum values of objects with same keys

I have a data structure like this one.
It’s basiccally an array of objects.

const dataset = [
  {
    a: { total: 2, name: "red" },
    b: { total: 3, name: "gold" },
    c: { total: 6, name: "rose" },
  },
  {
    a: { total: 10, name: "red" },
    b: { total: 7, name: "purple" },
  },
  {
    a: { total: 1, name: "pink" },
    b: { total: 14, name: "blue" },
    c: { total: 10, name: "rose" },
  },
  {
    b: { total: 2, name: "green" },
    c: { total: 18, name: "rose" },
  },
]

This is what I would like to compute as result:

const result = { 
  a: 13, 
  b: 26, 
  c: 34, 
}

So, I need a sum of values total by objects with same key.I try to explain myself using the previous example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const result = { 
  a: 13, // 2 + 10 + 1
  b: 26, // 3 + 7 + 14 + 2
  c: 34, // 6 + 10 + 18
}

Note that the keys a, b, c can be a lot (not only 3) and I don’t know their name because they are dynamic.

How can I do that? I thought to group the objects {total, name} by keys and then sum by total but how? Is there a Lodash function that can help me?

>Solution :

Why not use reduce with for of:

const dataset = [{a: { total: 2, name: "red" }, b: { total: 3, name: "gold" }, c: { total: 6, name: "rose" }, }, {a: { total: 10, name: "red" }, b: { total: 7, name: "purple" }, }, {a: { total: 1, name: "pink" }, b: { total: 14, name: "blue" }, c: { total: 10, name: "rose" }, }, {b: { total: 2, name: "green" }, c: { total: 18, name: "rose" }, }, ];

const result = dataset.reduce((res, cur) => {
    for (const [key, value] of Object.entries(cur)) {
      res[key] = (res[key] || 0) + value.total;
    }
    return res;
}, {});

console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading