Redefining JavaScript loops – filter map and reduce

 

In JavaScript we have been writing loops , like we do in any programming language . Today we are going to check JavaScript  filter , map and reduce . These are a part of JavaScript Functional Programming .

We are not going to deep dive into the concepts of functional programming in java script . Let’s get started and have  a look at these concepts with examples.

Have a look what MDN Says about these JavaScript filter map and reduce :-

  1. Filter In Javascript  :- As the name suggests, it returns an array with filtered  items from the original array
  2. Map In Javascript :- Used to create a new array by iterating existing array
  3. Reduce  In Javascript  :- Returns a single object .

We are going to take following example where we have an array of employees and we are going to do some operations on this array to demonstrate JavaScript filter map and reduce.




How to use Filter In JavaScript  :-

How Would you Find Out Employees Whose age is less than 50 here in above employee array ?

In a Normal JavaScript we would do something below as shown ,

let seniorCitizen = [];
for(let i = 0; i < employee.length; i++) {
  if(employee[i].age <= 50) {
    seniorCitizen.push(employee[i]);
  }
}

Now We have a different Way of Doing this using Javascript Filter .

const seniorCitizen= employee.filter(function(emp,index) {
    console.log(index);
      if(emp.age <= 50) {
        return true;
      }
    });

JavaScript Filter we can pass two arguments inside a callback function , actual object and index .

We can also Write same thing using ES6 syntax as below .

const seniorCitizen= employee.filter((emp,index) => {emp.age <= 50});

Output:-

How to use JavaScript Map  :-

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

const usernames = employee.map(function(emp) {
  return emp.name;
});

const test1 = employee.map(function(emp) {
  return `${emp.name} [${emp.age} - ${emp.salary}]`;
});

const testMap = employee.map(emp => `${emp.name} [${emp.age} - ${emp.salary}]`);

const ageMap = employee
  .map(emp => emp.age * 2)
  .map(age => age+2).filter(age=>age<88);

console.log(ageMap);
console.log(test1);
console.log(testMap);

Output :-

 Array(1) [48]
 Array(3) ["Sanjay [23 - 34545]", "John [43 - 3444]", "Sean [53 - 344445]"]
 Array(3) ["Sanjay [23 - 34545]", "John [43 - 3444]", "Sean [53 - 344445]"]

How to Use JavaScript Reduce :- reduce()  works on an array and returns a single object .We are going to write a code works on an array and reduce to compute the total value of age of users  array .

Lets See How We can achieve this :-

const ageSum = employee.reduce(function(total, emp) {
  return total + emp.age;
}, 0);

In the above example we are passing two parameters to the callback function , total is known as accumulator. The Job of accumulator is it accumulates the callback’s values . It is the accumulated value previously returned . In this case we have initialized our accumulator with zero value .

So once the first element of array is traversed accumulator total will have 0+age of First employee. Now this value is passed to the next callback function for second array item and so on.

Now We Can simplify the above JavaScript reduce() code using ES6 syntax as :

const totalYears = employee.reduce((total, emp) => total + (emp.age), 0);

Please Comment if You Want some More examples or You are stuck at any place .We will be happy to help you ! Thanks !