I have an array like this.
[{
PropertyOne : 1,
PropertyTwo : 5
},
{
PropertyOne : 3,
PropertyTwo : 5
},...]
And I want to end up with an array like this which aggregates all the columns of this array to end up like this.
[{
PropertyOne : 4,
PropertyTwo : 10
}}
If it was a single column I know I could use .reduce but can't see how I could do with multiple columns ?
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;
}, {});
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;
}, {});
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