Reputation: 269
I have an array of objects, and I'm trying to sum all the num
s in the array. The array looks like this:
var arr = [{"year": 2011, "num": 0}, {"year": 2012, "num": 2}, {"year": 2013, "num": 5}];
So the sum should be 7.
How do you calculate the total in Javascript?
I tried:
var sum = arr.reduce(function(a, b) {
return a + b;
});
But this returns:
"[object Object][object Object][object Object]"
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Upvotes: 0
Views: 242
Reputation: 44851
You just need to loop over the array and increment a variable:
var arr = [{"year": 2011, "num": 0}, {"year": 2012, "num": 2}, {"year": 2013, "num": 5}];
var sum = 0;
for(var obj in arr) {
sum += arr[obj].num;
}
// sum now contains the value 7
Here's a working jsFiddle to demonstrate.
Upvotes: 0
Reputation: 74695
Sounds like you want to reduce an array of values to a single value. Use reduce
:
var a = [{"year": 2011, "num": 0}, {"year": 2012, "num": 2}, {"year": 2013, "num": 5}];
a.reduce(function(prev, curr) { return prev + curr.num }, 0);
7
reduce
goes through each element of the array and accumulates a value using the function you pass it. The last argument is the initial value of prev
.
This has "only" been in the ECMAScript Language specification since 2011, so if you need to support old browsers, you might like to try something like underscore.js:
_.reduce(a, function(prev, curr) { return prev + curr.num }, 0);
This will fall back to the native implementation if such a thing exists.
Or if you like to roll your own, you can use a loop:
for (var i = 0, sum = 0; i < a.length; ++i) {
sum += a[i].num;
}
Upvotes: 4
Reputation: 633
You can use Array.prototype.map to turn it into an array of numbers, then Array.prototype.reduce to sum them:
var array = [{"year": 2011, "num": 0}, {"year": 2012, "num": 2}, {"year": 2013, "num": 5}];
var sum = array.map(function (a) {
return a.num;
}).reduce(function (a, b) {
return a + b;
});
Upvotes: 1
Reputation: 1924
var arr = [{"year": 2011, "num": 0}, {"year": 2012, "num": 2}, {"year": 2013, "num": 5}];
var sum = 0;
arr.forEach(function(obj){
sum += obj.num;
});
//now sum have 7
console.log(sum);
Upvotes: 1
Reputation: 2940
This should do it...
function getSum(theArray){
var sum = 0;
for(var i = 0; i<theArray.length; i++){
var sum += theArray[i].num
}
return sum;
}
Upvotes: 1
Reputation: 1643
var arr = [{"year": 2011, "num": 0}, {"year": 2012, "num": 2}, {"year": 2013, "num": 5}];
var sum = 0;
for(var i = 0; i < arr.length; i++) {
sum = sum + arr[i].num;
}
Upvotes: 3