Reputation: 305
Say I have the following array:
var BUILDINGS = [
{ production: {"numberProd": 6}},
{ production: {"numberProd": 11}},
{ production: {"numberProd": 14}},
];
I'm trying to use reduce()
to add up the sum of these productions. I've tried to the following:
BUILDINGS.reduce(function(a,b) {return a.production.numberProd + b.production.numberProd});
But when I run the code I get the value NaN
.
I was wondering how to properly set up the reduce()
statement.
Thank you!
Upvotes: 0
Views: 108
Reputation: 68933
You have to pass initial value of 0
which will be assigned to the first parameter a
in the initial iteration of reduce()
.
Try the following:
var BUILDINGS = [
{ production: {"numberProd": 6}},
{ production: {"numberProd": 11}},
{ production: {"numberProd": 14}},
];
var prod = BUILDINGS.reduce(function(a,b) {
return a + b.production.numberProd;
}, 0);
console.log('Total:', prod);
Upvotes: 5
Reputation: 11805
You were very close:
BUILDINGS.reduce(function(a,b) {return a + b.production.numberProd}, 0);
BUILDINGS.reduce((currentValue, nextBuilding) => {
return currentValue + nextBuilding.production.numberProd
}, 0) // 0 is the first value
Upvotes: 1
Reputation: 23859
You can do it like this:
var BUILDINGS = [
{ production: {"numberProd": 6}},
{ production: {"numberProd": 11}},
{ production: {"numberProd": 14}},
];
console.log(BUILDINGS.reduce((sum, item) => {
sum += item.production.numberProd;
return sum;
}, 0));
If you don't pass the initial value as 0
, you will get a NaN
as the result.
Upvotes: 0