Search code examples
javascriptarrayssum

How do I sum of similar properties in array of objects


I asked a similar question earlier today, but the output of this question is different. I asked wrongly the first time :(

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 :)

[7, 10]


Solution

  • let arr = [
        {"item1": 3, "item40": 2},
        {"item1": 4, "item40": 8}
      ]
      
    const res = Object.keys(arr[0]).map(key => arr.reduce((acc, cur) => acc + parseInt(cur[key] || 0), 0))
      
    console.log(res)