The reduce
method is applied to arrays in Javascript. This method does what its name says; it takes the values in an array, from the first till the last element, and applies functionality such that it changes the array into one singular value. Hence, it reduces the array.
The reduce
method helps make the code more concise and neat.
The reduce
method has the following syntax:
//Implementation Onelet answer = array.reduce(callback, initialValue);//Implementation Twolet answer = array.reduce(callback);// Expanding callbacklet answer = array.reduce(function(totalResult,currValue,currIndex,array),initialValue);
Now let’s understand what each value signifies:
answer
: This is the variable in which the final reduced value is to be stored.array
: This is the array on which the reduce method is applied.callback
: This is the method which is to be applied on each element of the array.The callback itself takes in four arguments:
totalResult
: This is the final total of returned values of all callbackscurrValue
: The value of the current elementcurrIndex
: The index of the currValue
array
: The array on which the reduce method is being appliedNote:
currIndex
andarray
are optional arguments.
initialValue
- this is an optional argument. This is passed to the reduce method as an initial value if you need to begin with a starting parameter.Let’s see how to find the total product of all values in the array using reduce
to really understand how it works.
In the example above, in Method 1, note that from lines 8 to 10, we call the reduce
method on array
. The callback takes in two parameters;
totalResult
which stores the cumulative result of all callbackscurrValue
which is the current element the callback is operating onThe callback method itself simply equates the totalResult
to the product of the two parameters.
In this implementation, there is no initialValue
and hence it simply starts with the array’s first element.
In the implementation from lines 16 to 17, the reduce
method has an initialValue
set to 2. Hence, in this case, the totalResult
is multiplied first with this value and then proceeds further.
In the second example, Method 2, the same functionality is implemented, except this time, the callback function is put in a separate method and that is called as the first argument of the reduce
method.