Refreshing JavaScript – Reduce Method – Detailed Explanation

Sathish Nadarajan
 
Solution Architect
May 2, 2019
 
Rate this article
 
Views
517

Definition:

.reduce() – A method which iterates through an array or collection and returns a reduced object.  The speciality is, the object which returns will be given as input for the next iteration.  To be more detailed, the reduce method can have a callback function, for which, the previous object in the array will become the input.  If it is not clear, let us have a look on the Example, so that we can understand much.

Example:

I have an Array of Employees.

 employees = [
             {
                 id:10,
                 Age:30
             },
             {
                 id:11,
                 Age:27
             },
             {
                 id:13,
                 Age:40
             }
         ];
 

In this array, I want to identify, which employee is the aged one.  For that, the output, I am expecting is a single object from the array.  I don’t want to do a for loop to identify this.  Instead, we can use the Reduce method.

 var agedEmployee = employees.reduce(function(oldest,employee){
             return (oldest.Age || 0) > employee.Age ? oldest : employee
         });
 
         console.log(agedEmployee); 
 

The same with the arrow operator is as below.

 var agedEmployee = employees.reduce((oldest,employee) => {return (oldest.Age || 0) > employee.Age ? oldest : employee  ;});
 console.log(agedEmployee); 
 

Here, the reduce method gets two parameters.

  • Oldest – A null value argument which is passed by me.
  • Employee – The object in the array.

 

  • During the first iteration, Oldest will be null, hence we are returning employee. This object, will become the first parameter (oldest) for the second iteration.
  • By that way, during the second iteration, the parameter ‘oldest’ will have {id:10, Age:30} and the parameter ‘employee’ will have {id:11, Age:27}

 

In case, If I want to add all the employees age, then the below will do that.

 var totalAge = employees.reduce((age,employee) => {
             return age + employee.Age; 
         },0);
 
         console.log(totalAge);
 

Here, the iteration will looks like,

IterationAgeEmployee.Age
1030
23027
35740

 

And the total would be 97.

Hope that helps and in the upcoming articles, we will see some other method.

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment