JavaScript Reduce Method
There are many arrow methods in JavaScript like map, filter, find and what not. Reduce is one of them but a little confusing to some of us. Today we’re going to clear that out.
Reduce method can be used to get the sum of some elements. Like if we have an array called nums
-
const nums = [1,2,3,4,5,6,7,8,9,10];
Then we want a variable total
to store the sum of the elements of nums
array. If we do that by using map method we’ll code -
const total = 0;
nums.map(num => total += num);
The map method takes a callback function having a parameter num
that stores each element of the nums
array and adds them to the total
variable. Thus we get a total of 55
. This same process can be done by using reduce with a fewer code -
const total = nums.reduce((sum, num) => sum + num, 0);
We are declaring the total
variable but instead of initializing it’s value with 0, we’re running the reduce method in it. The reduce method takes two parameters. First one is a callback function which would have another two parameters, one for storing the sum, and another for storing each elements like the map method. Second one is the initial value of the callback functions first parameter.
So, here in our reduce method, we used a callback function with two parameters sum
and num
, and we are initializing the sum
with that 0
. As it is sum = 0
. Then the num
parameter is going to store the elements of the nums
array and add them into the sum
. That means sum
is going to store the sum of the elements. Just like what map method did. And at last, the total
variable is going to have the sum
’s value.
So, in a one line code, the total
variable is having the sum 55
. Hope that’s enough to understand reduce method. Taking you leave, Assalamualaikum :)