Skip to content Skip to sidebar Skip to footer

Sum Of Fields In An Array Of Objects With Reduce Returns Nan

I am seeing a strange behaviour with the reduce function in javascript. I have an array of objects, made like this: [ { a:1 }, {a:2}, ... ] I need the sum of the a property inside

Solution 1:

When using Array.reduce(), if you don't state an initial value, the 1st item of the array becomes the initial value. Since you want a number, and not an object as the result, initialize with 0. Since the accumulator is now a number, and not an object, use accumulator instead of accumulator.a in the function's body:

const array = [{a:1}, {a:2}, {a:3}];
constreducer = (accumulator, currentValue) => accumulator + currentValue.a;
console.log(array.reduce(reducer, 0));

You can also check if the accumulator is an object, and then try to access it's property, but I find it more confusing than simply stating an initial value:

const array = [{a:1}, {a:2}, {a:3}];
constreducer = (accumulator, currentValue) => (typeof accumulator === 'object' ? accumulator.a : accumulator) + currentValue.a;
console.log(array.reduce(reducer));

Solution 2:

Your reducer returns a number value (sum of accumulator.a + currentValue.a) while your accumulator is an object.

Either initialize accumulator to 0 or return the accumulator itself, make it

constreducer = (accumulator, currentValue) => (accumulator.a += currentValue.a, accumulator);

Demo

const array = [{
  a: 1
}, {
  a: 2
}];
constreducer = (accumulator, currentValue) => (accumulator.a += currentValue.a, accumulator);
console.log(array.reduce(reducer, {
  a: 0
}));

Note

  • This reducer will return {"a":3}, but if you only want the sum value, print its property a

i.e.

console.log(array.reduce(reducer, {
  a: 0
}).a);

Solution 3:

You need to change your reducer function as

constreducer = (accumulator, currentValue) => ({ a: accumulator.a + currentValue.a });

your orignal code doesn't work as you return a Number instead of an object whose property you were accessing.

Post a Comment for "Sum Of Fields In An Array Of Objects With Reduce Returns Nan"