Use the Array reduce() method to sum an array of objects in JavaScript. This method applies a function against an accumulator and each value of the array (from left to right) to reduce it to a single value.
By using a combination of reduce()
and accessing the desired property within each object, you can quickly and easily calculate the sum.
JavaScript sum array of objects
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
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);
</script>
</body>
</html>
Output:
One line solution for the same but adding all values of object property
<script>
var array = [{"adults":2,"children":3},{"adults":2,"children":1}];
var totalChild = array.reduce((accum,item) => accum + item.children, 0)
console.log(totalChild)
</script>
Output: 4
You can write a function for this task, which gets the array to iterate over a property, which value should be added.
The key feature of the function is the Array#reduce method and a property that returns the actual count value 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>');
Output:
Adults: 4
Children: 5
Comment if you have any doubts or suggestions on this JS Array topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version