You should pass the initial argument as well :
ourArray.reduce((accumulator, currentValue) => { return accumulator * currentValue }, 1)
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
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
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.
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.