0

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!

Mamun
  • 66,969
  • 9
  • 47
  • 59
bejewelled
  • 195
  • 13
  • Possible duplicate of [Javascript reduce on array of objects](https://stackoverflow.com/questions/5732043/javascript-reduce-on-array-of-objects). How to properly set up `reduce` is described in the [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce). – Sebastian Simon Apr 20 '18 at 04:55

3 Answers3

5

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);
Mamun
  • 66,969
  • 9
  • 47
  • 59
1

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
Isaac
  • 11,409
  • 5
  • 33
  • 45
0

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.

31piy
  • 23,323
  • 6
  • 47
  • 67