Say I want to sum a.x for each element in arr.
arr = [ { x: 1 }, { x: 2 }, { x: 4 } ];
arr.reduce(function(a, b){ return a.x + b.x; }); // => NaN
I have cause to believe that a.x is undefined at some point.
The following works fine
arr = [ 1, 2, 4 ];
arr.reduce(function(a, b){ return a + b; }); // => 7
What am I doing wrong in the first example?
After the first iteration your’re returning a number and then trying to get property
xof it to add to the next object which isundefinedand maths involvingundefinedresults inNaN.try returning an object contain an
xproperty with the sum of the x properties of the parameters:Explanation added from comments:
The return value of each iteration of
[].reduceused as theavariable in the next iteration.Iteration 1:
a = {x:1},b = {x:2},{x: 3}assigned toain Iteration 2Iteration 2:
a = {x:3},b = {x:4}.The problem with your example is that you’re returning a number literal.
Iteration 1:
a = {x:1},b = {x:2},// returns 3asain next iterationIteration 2:
a = 3,b = {x:2}returnsNaNA number literal
3does not (typically) have a property calledxso it’sundefinedandundefined + b.xreturnsNaNandNaN + <anything>is alwaysNaNClarification: I prefer my method over the other top answer in this thread as I disagree with the idea that passing an optional parameter to reduce with a magic number to get out a number primitive is cleaner. It may result in fewer lines written but imo it is less readable.