What is Array.prototype.reduce?
The reduce method executes a reducer function (provided by you) on each element of the array, resulting in a single output value. The reducer function takes four arguments:
1.Accumulator: The accumulated value previously returned by the last invocation of the callback, or the initialValue if supplied.
2.Current Value: The current element being processed in the array.
3.Current Index: The index of the current element being processed.
4.Source Array: The array on which reduce was called.
array.reduce(reducerCallbackFn,initialValue)
Lets start with basic implementation of reduce
Initializing the Accumulator
let accumulator=initalValue!==undefined?initalValue:this[0]
The accumulator is the value that will be updated with each iteration of the loop. If an initialValue is provided, it is used as the starting value for the accumulator. otherwise, the first element of the array (this[0]) is used as the initial value.
Determining the Start Index
let startIndex = initialValue !== undefined ? 0 : 1;
If an initialValue is provided, the loop should start from index 0 otherwise, it should start from index 1 because the first element is already used as the initial value for the accumulator.
Iterating Over the Array
The loop iterates over the array, starting from the appropriate index. For each element, the callback function is called with the following arguments:
1.Accumulator: The current accumulated value.
2.Current Value: The current element (this[i]).
3.Current Index: The index of the current element (i).
4.Source Array: The array itself (this).
The result of the callback function is assigned back to the accumulator.
Top comments (2)
Very well explained!
Nicely explained