Javascript Reduce
Hi friends, in this article, I will explain the Javascript reduce() method. Reduce method is one of the array methods. But Reduce method is a little bit complicated than the other array methods.
Definition for Reduce method
The reduce() method applies a reducer function to each array element and returns a single value.
The way Reduce function works
The reduce function has the following parts in its callback.
- accumulator
- currentValue
- currentIndex (optional)
- array (optional)
- initialValue (optional)
accumulator:
The accumulator accumulates the callback function’s return value. If it has initialValue, in the callback function the first time accumulator’s value should be the initialValue, Otherwise, it should be the first element of the array.
currentValue:
The current element being processed in the array.
currentIndex:
The index of the current element being processed in the array. It is an optional field.
array:
The array passed in the reduce method. It is an optional field.
initialValue:
Using the initialvalue
set the first argument of the first callback function. If there is no initialValue
then it takes the first element of the array as initialValue
. It is an optional field.
If you passed an empty array in the reduce()
method without initialValue
it throws TypeError.
Using reduce() method we can accomplish several things. But here I give two examples.
Example 1:
In this simple example, we will get the sum of the array element.
Traditional approach:
In the above example code using for-loop
, we can get the sum of array elements. But here we need to write more codes.
We accomplish the sum of array elements in a single line of code using the reduce()
method.
Reduce method:
Look at the above example we have set 0 for initialValue
. The below image shows how the accumulator
and currentValue
processing in the loop each time.
Example 2:
Changing the structure of the object using reduce method.
In the above example, I changed the order of the object. id
is the unique value in the array of object. Now changed id
to the key and assigned the object to the id
.
In this article, I gave only two different examples using reduce(). But we can do more thing using reduce().
Thank you for reading. Have a nice day.