Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum values of objects in array

I would like to create a sum of an array with multiple objects.

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

How do I return the sum of adults and the sum of children into a new variable for each?

Thanks, c.

like image 352
chimichanga Avatar asked Feb 18 '16 11:02

chimichanga


People also ask

How do you sum values in array of objects?

To sum a property in an array of objects:Initialize a sum variable, using the let keyword and set it to 0 . Call the forEach() method to iterate over the array. On each iteration, increment the sum variable with the value of the object.

How do you sum multiple objects with the same key in an array?

How do you sum multiple objects with the same key in an array? First iterate through the array and push the 'name' into another object's property. If the property exists add the 'value' to the value of the property otherwise initialize the property to the 'value'.


4 Answers

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);
like image 124
Rayon Avatar answered Oct 07 '22 23:10

Rayon


 

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

var totalChild = array.reduce((accum,item) => accum + item.children, 0)

console.log(totalChild) //output 4
like image 31
DINESH Adhikari Avatar answered Oct 07 '22 23:10

DINESH Adhikari


Seeing nobody posted this yet... here is a nice shorthand method:

.reduce((acc, curr) => acc + curr.property, 0)

Example:

arr = [{x:1, y:-1}, {x:2, y:-2}, {x:3, y:-3}];

x_sum = arr.reduce((acc, curr) => acc + curr.x, 0); // 6
y_sum = arr.reduce((acc, curr) => acc + curr.y, 0); // -6
like image 43
Foxcode Avatar answered Oct 07 '22 22:10

Foxcode


You can write a function for this task, which gets the array to iterate over an the property, which value should be added.

The key feature of the function is the Array#reduce methode and a property which returns the actual count calue and the actual property value.

function count(array, key) {
    return array.reduce(function (r, a) {
        return r + a[key];
    }, 0);
}

var array = [{ "adults": 2, "children": 3 }, { "adults": 2, "children": 2 }],
    adults = count(array, 'adults'),
    children = count(array, 'children');

document.write('Adults: ' + adults + '<br>');
document.write('Children: ' + children + '<br>');
like image 2
Nina Scholz Avatar answered Oct 08 '22 00:10

Nina Scholz