Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS How to use reduce on array containing multiple numerical values

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 ?

like image 428
StevieB Avatar asked Oct 24 '16 18:10

StevieB


2 Answers

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;
}, {});
like image 127
Dan O Avatar answered Sep 25 '22 03:09

Dan O


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;
    }, {});
like image 20
Joel H Avatar answered Sep 25 '22 03:09

Joel H