The Mysterious Array.reduce() Method in JavaScript
The array.reduce() method is famous for summing up an array of numbers.
var arr = [1,2,3];
var sum = arr.reduce((x,y)=>{
return x + y
});
console.log(sum);
//6
It can be also used go conduct a series of substraction starting from the first number.
var arr = [100,50,10];
var remaining = arr.reduce((x,y)=>{
return x - y
});
console.log(remaining);
//40
Or, the array.reduce() method can be used to execute a series of multiplication or division.
var arr1 = [1,2,3,4];
var fac = arr1.reduce((x,y)=>{
return x * y
});
console.log(fac);
//24
var arr2 = [100,5,4];
var fac = arr2.reduce((x,y)=>{
return x / y
});
console.log(fac);
//5
What Actually Happened Inside the Array.reduce() Method?
What happs inside the arrray.reduce() method is that it keeps the return value as a parameter for the next itiration of the calculation until all elements of the array are gone through. And the initial return value or element, since no calculation has been executed, will be the first element of the array.
In the summation example above, in [1,2,3], the initail proxy return value is 1 which is kept as x in this statement "return x + y" where y is the next value 2. Then 1 + 2 is executed and returns 1 + 2 = 3, then 3 is kept as x, replacing the original value of 1. The itiration goes again for the next value in the array until all numbers are run through. The final return value will be given out.
var arr1 = [1,2,3];
var sum = arr1.reduce((x,y)=>{
console.log(x);
return x + y;
});
//1
//3
var arr2 = [1,2,3];
var sum = arr2.reduce((x,y,i)=>{
console.log(i);
return x + y;
});
//2
//3
Other Parameters in the Array.reduce() Method
Beside x, the place the hold return value and y the next value to be applied in the calculation, we can call the index of the y element. Here, we won't see the index 0, since the first index of y is the second element in the array. The first element is already taken as the proxy return value in the first itiration.
var arr = [10,20,30,40,50];
var sum = arr.reduce((x,y,i)=>{
console.log(i);
return x + y;
});
//1
//2
//3
//4
We can also call the original array inside of the redece loop.
var arr = [10,20,30,40,50];
var sum = arr.reduce((x,y,i,a)=>{
console.log(a);
return x + y;
});
//[10,20,30,40,50]
//[10,20,30,40,50]
//[10,20,30,40,50]
//[10,20,30,40,50]
This is useful when we want to do something at the end of the itiration. For example, we can obtain the mean from an array of numbers.
var arr = [1,2,3,4,5];
var mean = arr.reduce((x,y,i,a)=>{
var l = a.length;
if(i == l-1){
return (x+y)/l;
};
return x + y;
});
console.log(mean);
//3
Comments
Post a Comment