I have an array of objects like this : const array=[{a:1, b:1} , {a:2, b:3} ,{a:1, b:1}]
i want an array like results = [{a:4 , b:5}] which is the sum of all values from the array of objects according to the key .
I tried something like this but sometimes it skipping the 1st object in the array :
array.reduce((acc, n) => {
for (var prop in n) {
if (acc.hasOwnProperty(prop)) acc[prop] += n[prop];
else acc[prop] = 0;
}
return acc;
}, {})
You need to initialize acc before assigning, so small modification below will work
const array=[{a:1, b:1} , {a:2, b:3} ,{a:1, b:1}]
const res = array.reduce((acc, n) => {
for (var prop in n) {
acc[prop] = acc[prop] || 0; // Need to initialize before assigning
if (n.hasOwnProperty(prop)) {
acc[prop] += n[prop];
}
}
return acc;
}, {})
console.log(res);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With