Reduce method does not work

You should pass the initial argument as well :

ourArray.reduce((accumulator, currentValue) => { return accumulator * currentValue }, 1)

Hello I tried it outā€¦ It works!!!.. but I donā€™t quite understand how it works :sweat_smile:

At every step, the reducer function takes the provided arguments (the accumulator, the current value, and the unused arguments here: the index of the current value, and the array) and puts the result in the accumulator for the next step.
If you donā€™t return anything, the accumulator will be undefined and the next step will try to multiply the current value with undefined

1 Like

Just to be clear, you donā€™t have to provide an initial value to reduce. If you donā€™t, it just uses the first value of the array as the initial and skips to the second iteration (not running the first).

So, the different between these two:

[3, 2, 4, 1, 5].reduce(((a, c)=> a + c), 0)
[3, 2, 4, 1, 5].reduce((a, c)=> a + c)

is that the first will start with 0 and do 5 iterations and the second will start with 3 and do 4 iterations (skipping the iteration for the first element). There are times where that works fine. Often not, but sometimes in simple reducers like this.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.