Let's first understand what reduce is?
Consider this following custom implementation:
const arr = [{ a: 1 }, { b: 5 }, { c: 2 }];
const reduced = (array, instructionToCombine, buildingUpOn) => {
for (let i = 0; i < array.length; i++) {
buildingUpOn = instructionToCombine(buildingUpOn, array[i][Object.keys(array[i])]);
}
return buildingUpOn;
}
const instructionToCombine = (a, b) => a + b;
const ans = reduced(arr, instructionToCombine, 0);
console.log(ans)
Now, you got how JavaScript default reduce method works.
You're missing the initialValue (buildingUpOn in my implementation). Know that, initialValue is not required parameter, rather it's optional. Yet,
If no initialValue is supplied, the first element in the array will be
used as the initial accumulator value and skipped as currentValue - MDN
But you treated otherwise that's why didn't get the expected answer. acc is a object for the first iteration, but rest of the iteration it's a number but you treated like a object which returned undefined and, sum of a Number with undefined returns NaN.
If you still need to achieve this without passing the initialValue, it's very possible by keeping acc an object this way:
const arr = [{ a: 1 }, { b: 5 }, { c: 2 }];
const app = (arr) => {
const r = arr.reduce((acc, nextValue) => {
const newValue = acc[Object.keys(acc)] + nextValue[Object.keys(nextValue)];
return {x: newValue};
})
return r[Object.keys(r)];
}
console.log(app(arr))
acc[Object.keys(acc)] + nextValue[Object.keys(nextValue)]does?Object.keys()returns an array. In this case it works, but only because there's only one property in every object.console.log()in the.reduce()and check the valuesreduce. But moreover, you're not using thereducecallback correctly - note that the return value becomesaccnext time the callback is invoked, so if you return a numberacc[Object.keys(acc)]will try to get a property off a number. Finally[Object.keys(acc)]itself is a potential problem, asObject.keysreturns an array and in most cases, that will not fetch anything specific from an object.