Categories

# Reduction Methods

JavaScript also introduced two reduction methods for arrays: reduce() and reduceRight(). Both methods iterate over all items in the array and build up a value that is ultimately returned.

The reduce() method does this starting at the first item and traveling toward the last, whereas reduceRight() starts at the last and travels toward the first. Both methods accept two arguments: a function to call on each item and an optional initial value upon which the reduction is based. The function passed into reduce() or reduceRight() accepts

four arguments: the previous value, the current value, the item’s index, and the array object. Any value returned from the function is automatically passed in as the first argument for the next item. The first iteration occurs on the second item in the array, so the first argument is the first item in the array and the second argument is the second item in the array.

You can use the reduce() method to perform operations such as adding all numbers in an array. Here’s an example:

``````var values = [1,2,3,4,5];
var sum = values.reduce(function(prev, cur, index, array){
return prev + cur;
});
alert(sum); //15``````

The first time the callback function is executed, prev is 1 and cur is 2. The second time, prev is 3 (the result of adding 1 and 2), and cur is 3 (the third item in the array). This sequence continues until all items have been visited and the result is returned. The reduceRight() method works in the same way, just in the opposite direction. Consider the following example:

``````var values = [1,2,3,4,5];
var sum = values.reduceRight(function(prev, cur, index, array){
return prev + cur;
});
alert(sum); //15``````

Examples

Take an array of numbers and print the sum of all the numbers using reduce method.

``````var ar = [12,33,66,24,56,34,21];

var total = ar.reduce(function(a,b){
return a+b;
});
console.log(total);``````

Take an array of numbers and find out the maximum number in the array using the reduce method.

``````var ar = [1,22,13,14,5,16,7,8];

var max = ar.reduce(function(a,b){
if(a<b){
return b;
}
else{
return a;
}
});
console.log(max);``````

Take an array of objects containing name and salary of a few people and find out the average salary using the reduce method.

``````var employees = [
{
name:'Hari',
sal:40000
},
{
name:'Ravi',
sal:45000
},
{
name:'Kishore',
sal:60000
},
{
name:'Madan',
sal:52000
}
];

var totalSalary= employees.reduce(function(a,b){
if(a instanceof Object){
return a.sal+b.sal
}
else{
return a+b.sal;
}
});
console.log("Avg Salary::",totalSalary/employees.length);``````