I have an array of objects that looks like this:
[
{1: 22},
{1: 56},
{2: 345},
{3: 23},
{2: 12}
]
I need to make it look like this:
[{1: 78}, {2: 357}, {3: 23}]
Is there a way I could make it so that it can sum up all the values that have the same key? I have tried using a for each loop but that hasn't helped at all. I would really appreciate some help. Thank you!
You can use reduce
for this to build up a new object. You start with an empty object and set the key to the value from the original array or add it to an existing object already. Then to get an array, just map it back.
let arr = [{1: 22},{1: 56},{2: 345},{3: 23},{2: 12}];
let tot = arr.reduce((a,obj) => {
let [k, v] = Object.entries(obj)[0]
a[k] = (a[k] || 0) + v
return a
}, {})
let final = Object.entries(tot).map(([k,v]) => {
return {[k]:v}
})
console.log(final);