I was wondering why the index in array.reduce()
starts from 1 rather than 0 in the below example
([11,22,33,44]).reduce((acc, val, index) => console.log(val));
//This outputs 22, 33 and 44 and skips 11
The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
The reduce() method does not change the original array.
array. reduce(callback, initialValue) accepts 2 arguments: the callback function that updates the accumulator value, and the initial value of the accumulator. array. reduce() then invokes the callback for each item of the array, updating the accumulator at each step.
If initialValue is provided in the call to reduce , then accumulator will be equal to initialValue and currentValue will be equal to the first value in the typed array. If no initialValue was provided, then accumulator will be equal to the first value in the typed array and currentValue will be equal to the second.
The accumulator takes the first value if you don't pass a value as the second argument:
// add a vlaue to start
([11,22,33,44]).reduce((acc, val, index) => console.log(val), 0);
// now all values are iterated
If you log the accumulator you can see how all the values are used without the second arg:
// Show accumulator return value
let final = ([11,22,33,44]).reduce((acc, val, index) => (console.log("acc:", acc, "val:", val), val));
// final is the last object that would have been the accumulator
console.log("final:", final)
Cause .reduce
is designed to work without an initial accumulator:
[1, 2, 3].reduce((a, b) => a + b)
For this to work, a
will be the first element and b
the second one at the first iteration, the next one will take the previous result and the third value.
If you pass an initial accumulator as the second argument, it will start at index 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With