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)
Shawn Cao
  • 117
  • 7
  • 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) 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). – Sebastian Simon Oct 13 '20 at 05: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. – Sebastian Simon Oct 13 '20 at 05:50
  • thank you for the explanation - @user4642212 – Shawn Cao Oct 13 '20 at 06:29

0 Answers0