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)
[ {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).reducecall less confusing, so prefer using it. “removing the initial value param will work properly” — no: try three elements.