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.
-
'into a new variable for each' means a single variable or different variables for each of essences?RomanPerekhrest– RomanPerekhrest2016年02月18日 12:03:21 +00:00Commented Feb 18, 2016 at 12:03
-
2similar: Better way to sum a property value in an arrayPat Myron– Pat Myron2025年09月26日 03:47:44 +00:00Commented Sep 26 at 3:47
9 Answers 9
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);
9 Comments
object part in one of the version but later I thought it will make more sense to return it as object than array..I am ready to delete this answer if you want me to... How much difference it is going to make ?
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
Comments
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
1 Comment
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>');
Comments
var array = [{"adults":2,"children":3},{"adults":2,"children":1}];
var sumProps = prop => (sum, obj) => sum += obj[prop];
var adultsCount = array.reduce( sumProps('adults'));
var childrenCount = array.reduce( sumProps('children'));
Comments
To get a sum of each essence into separate variable:
var array = [{"adults":2,"children":3},{"adults":2,"children":1}];
var adults_sum = 0, children_sum = 0;
array.forEach(function(obj){
adults_sum += obj["adults"];
children_sum += obj["children"];
});
console.log(adults_sum, children_sum); // 4 4
Comments
We are not writing code for you, but I suppose you should try:
var val = array.reduce(function (sum, tuple) {
return { adults: sum.adults + tuple.adults,
children: sum.children + tuple.children };
});
Comments
Here is a fun exercise in functional programming. Assuming you already have a sum function for simple arrays of numbers, you can implement a function that will sum the totals of all keys over an array of objects in just two expressions. No loops, hardcoded property names, anonymous functions or if/else required. I adopted the following code from my answer to How to get an object containing the sum of all items in an arrays of objects? :
var add = (a, b) => a + b;
var sum = _.partial(_.reduce, _, add, 0);
function sumByProperties(data) {
var keys = _.chain(data)
.map(_.keys).flatten().uniq().value();
return _.chain(keys).zip(keys).object()
.mapObject(_.property)
.mapObject(_.partial(_.map, data))
.mapObject(_.compose(sum, _.compact))
.value();
}
console.log(sumByProperties([{
apple: 1,
banana: 4,
fish: 2,
melon: 3,
}, {
apple: 3,
banana: 2,
fish: 5,
melon: 1,
}]));
<script src="https://cdn.jsdelivr.net/npm/[email protected]/underscore-umd-min.js"></script>
While the implementation of sumByProperties is not straightforward, figuring out how it works will deepen your understanding of functional programming. This will empower you to write some things very concisely, such as the definition of sum at the top.
For the convenience of the reader, here are links to the documentation of each Underscore function used in this snippet, by order of evaluation:
_.partial
_.reduce
_.chain
_.map
_.keys
_.flatten
_.uniq
_.value
_.zip
_.object
_.mapObject
_.property
_.partial
_.compose
_.compact
Comments
May be it can help you and this also without use reduce func.
var sumAdult=0;
var sumChildren=0;
var array = [{
"adult": 2,
"children": 3
}, {
"adult": 2,
"children": 1
}];
function x(a,b){
return a+b;
}
for (y in array){
sumAdult=x(0, array[y].adult);
console.log( "adult :" + sumAdult);
sumChildren=x(0, array[y].children);
console.log( "children :" + sumChildren);
}