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.
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? 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'.
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);
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
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
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>');
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