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!

1

3 Answers 3

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);

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Thank you so much!
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.