0

Can anybody explain why this returns NaN (chrome)?

[{value:1}, {value:2}].reduce((a,b)=>a.value+b.value, {value:0})

or

[{value:1}, {value:2}].reduce((a,b)=>a.value+b.value, 0)

removing the initial value param will work properly:

[{value:1}, {value:2}].reduce((a,b)=>a.value+b.value)

Or instead, using a map will work as expected:

[{value:1}, {value:2}].map(e=>e.value).reduce((a,b)=>a+b, 0)
3
  • 2
    The correct semantics are [ {value: 1}, {value: 2} ].reduce((sum, object) => sum + object.value, 0). The reducer function can be shortened to (sum, {value}) => sum + value. Read the documentation thoroughly; everything is explained there. The first argument is your accumulator, the second one is the next value of the array. If the starting value is provided, that’s your accumulator in the first iteration; otherwise, the first array element is used (next being the second element). Commented Oct 13, 2020 at 5:46
  • Including the starting value almost always makes the reduce call less confusing, so prefer using it. “removing the initial value param will work properly” — no: try three elements. Commented Oct 13, 2020 at 5:50
  • thank you for the explanation - @user4642212 Commented Oct 13, 2020 at 6:29

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.