Sum values of objects in array

Use Array.prototype.reduce(), the reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

var array = [{
  "adults": 2,
  "children": 3
}, {
  "adults": 2,
  "children": 1
}];

var val = array.reduce(function(previousValue, currentValue) {
  return {
    adults: previousValue.adults + currentValue.adults,
    children: previousValue.children + currentValue.children
  }
});
console.log(val);

Leave a Comment