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 every object, so I wrote this:
const array = [{a:1}, {a:2}];
const reducer = (accumulator, currentValue) => accumulator.a + currentValue.a;
console.log(array.reduce(reducer));
This works as expected.
If I try to run the same code with an array containing a single object, I get that object as the result of the reduce
call (and this is expected behaviour), so I added a default value to the reduce function call like this:
const array = [{a:1}];
const reducer = (accumulator, currentValue) => accumulator.a + currentValue.a;
console.log(array.reduce(reducer, {a: 0}));
And this also works like a charm.
I would expect to be able to run the second version of the reduce call with an array with more than one element, such as:
const array = [{a:1}, {a:2}];
const reducer = (accumulator, currentValue) => accumulator.a + currentValue.a;
console.log(array.reduce(reducer, {a: 0}));
But this returns NaN
and I don't understand why.
Could anyone please explain me?