Johansrk
Johansrk

Reputation: 5250

How can I find many sums in an array of objects

I have a large array, which I have simplified for the question purpose

[
  {"item1": 3, "item40": 2},
  {"item1": 4, "item40": 8}
]

I would like to end up with this, which is the sum of each similar property in the array of objects. I tried a lot. Doing a forEach whith a forIn inside. But I am stuck. Please help :)

[5, 12]

Upvotes: 0

Views: 36

Answers (2)

phi-rakib
phi-rakib

Reputation: 3302

You could use Array.prototype.map() with Array.prototype.reduce() to get the result. Traverse the array using map, get the object values using Object.values() and at last, sum the values using reduce.

const data = [
  { item1: 3, item40: 2 },
  { item1: 4, item40: 8 },
];
const ret = data.map((x) => Object.values(x).reduce((p, c) => p + c, 0));
console.log(ret);

Upvotes: 3

Alexander Nied
Alexander Nied

Reputation: 13623

This leverages .map to loop over the values in the array, then gets uses Object.values to get the values in each object as an array and [.reduce] to sum them:

const arr = [
  {"item1": 3, "item40": 2},
  {"item1": 4, "item40": 8}
];

const result = arr.map((obj) => Object.values(obj).reduce((acc, cur) => acc + cur, 0));

console.log(result);

Upvotes: 2

Related Questions