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