JS How to use reduce on array containing multiple numerical values
The same (as other answers) using ES6 arrow functions:
var reducedArray = array.reduce((accumulator, item) => {
Object.keys(item).forEach(key => {
accumulator[key] = (accumulator[key] || 0) + item[key];
});
return accumulator;
}, {});
var array = [{
PropertyOne : 1,
PropertyTwo : 5
},
{
PropertyOne : 2,
PropertyTwo : 5
}];
var reducedArray = array.reduce(function(accumulator, item) {
// loop over each item in the array
Object.keys(item).forEach(function(key) {
// loop over each key in the array item, and add its value to the accumulator. don't forget to initialize the accumulator field if it's not
accumulator[key] = (accumulator[key] || 0) + item[key];
});
return accumulator;
}, {});