11

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 ?

3
  • 1
    how you getting PropertyOne :6 ? Commented Oct 24, 2016 at 18:19
  • You have access to the full object in your reduce callback. Accumulate against each property and return the full object. Commented Oct 24, 2016 at 18:20
  • Shouldn't it be PropertyOne: 3 since 1 + 2 = 3? Commented Oct 24, 2016 at 18:56

2 Answers 2

16
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;
}, {});
Sign up to request clarification or add additional context in comments.

2 Comments

You can just wrap this in an array to get what you ask for specifically in your question (array of one object)
@ExplosionPills , good point! I missed that. var reducedArray = [array.reduce( /*... */ )];
7

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;
    }, {});

1 Comment

You could also wrap the accumulator with . if (typeof item[key] === 'number') { .... accumulatory[key].... }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.