Map⇄Filter⇄Reduce↻ – Hacker Noon

Array.prototype.reduce() || reduce() || ✂️

The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value→MDN

const arr = [3, 4, 2, 9];
const reduce=(accumulator, currentValue)=>accumulator+currentValue;
console.log(arr.reduce(reduce));
console.log(arr.reduce(reduce, 7));

In the above code, we create a reduce function which will be passed as a callback to the .reduce() function. The function returns the addition of all the elements in the array. The accumulator stores the sum of the elements after every iteration and currentValue represents the value currently processed. The default value of the accumulator is 0 and can also be user defined as done in the second console.log as 7. The accumulator is returned as a final result.

with for loop

const arr = [3, 4, 2, 9];
var a=0;
for(let
i=0;i{
a+=arr[i];
}
console.log(a);

From 3 lines we go to 7 lines.

reduce calls a provided callback function upon each element in the array and is called only for indexes for which the array contains a value.

The callback is given 4 arguments

  • accumulator
  • currentValue
  • currentIndex
  • array

The first time when the callback is called just before processing the first value the currentValue will be the first element in the array while the accumulator will have the value of the first element of the array or the value which is specified by the user in the reduce function.

If the accumulator is provided a value then reduce will start the callback from index 1 and skip the first index as accumulator already has the value of the first index. If initially the value is provided the callback will start from the first index.

The first time the callback is called, accumulator and currentValue can be one of two values. 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 array. If no initialValue is provided, then accumulator will be equal to the first value in the array, and currentValue will be equal to the second.

If the array is empty and no initial value is given to the accumulator, a TypeError is thrown.

It is usually safer to provide an initial value because there are three possible outputs without initialValue, as shown in the following example.

Let’s dissect it-

Parameters– The parameters taken by the reduce function is a callback function which in turn takes parameters accumulator, index, array & currentValue.

  • currentValue→ It is the current element which is processed by the reduce.
  • array|optional→The array on which the reduce was called upon.
  • index|optional→ The index of the current element which is being processed in the array.
  • accumulator|optional→ Value to use as the first argument on the first call of the callback.

Return-

reduce returns the value left after reduce is done(accumulator).

read original article here