Why `array.reduce()` starts from index 1
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.
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)