Reputation: 144
Note:I've been looking online, and even though i couldn't find the answer I was looking for I'm pretty sure its out there so please forward me to it if this has been answered. Sorry for the double post if there is one.
Hi, I'm trying to get the the values of one key inside a list of arrays. My Goal is to get the sum of a "column"
For example:
Heres my list of arrays
var total = 0;
var dataset= [
{"cost" : 5.00 , "name" : "Victor" },
{"cost" : 6.00 , "name" : "Jack" },
{"cost" : 7.00 , "name" : "Bill" },
{"cost" : 8.00 , "name" : "Delilah" },
{"cost" : 9.00 , "name" : "Robert" },
{"cost" : 10.00 , "name" : "Marisa" }
]
Is there any way to get the sum of all cost fields in one go. Or is there a way to get the cost values displayed as one array in one go?
if i get the all the values for the cost field i would want it to look like this:
[5.00,6.00,7.00,8.00,9.00,10.00]
If theres a built in function that im unaware about then i would get this:
total = dataset["cost"].sum(); <-- pseudo code
console.log(total) //would print 45
i want to avoid looping through each index of my dataset.
Thanks in advance
Upvotes: 0
Views: 64
Reputation: 69
You can sum all values from an Array with Array.prototype.reduce:
var total=[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, currentIndex, array) {
return previousValue + currentValue;
});
console.log(total)
Upvotes: 0
Reputation: 924
You don't need to iterate! You can use the handy procedures that JavaScript gives us!
To retrieve the sums of all the costs
, you can do this...
function sums( array ) {
return array.reduce(function(last, current) { return last + current['cost'] });
}
pass in dataset
to get the sum.
Upvotes: 1
Reputation: 1378
anyway you need to iterate through array. You can do it via array.reduce
var result = dataset.reduce(function(sum, current) {
return sum + current.cost;
}, 0);
Upvotes: 0