Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why `array.reduce()` starts from index 1

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
like image 291
Saksham Avatar asked May 02 '19 18:05

Saksham


People also ask

What is the reduce ()` array method?

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.

Does reduce change original array?

The reduce() method does not change the original array.

What is the second argument of reduce ()?

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.

How should the initial value of accumulator be provided in the reduce function?

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.


2 Answers

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)
like image 168
Mark Avatar answered Dec 15 '22 18:12

Mark


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.

like image 36
Jonas Wilms Avatar answered Dec 15 '22 19:12

Jonas Wilms