Bhakti Kharatkar
Bhakti Kharatkar's Blog

Bhakti Kharatkar's Blog

Understanding Map, Filter and Reduce functions in JavaScript.

Understanding Map, Filter and Reduce functions in JavaScript.

Bhakti Kharatkar's photo
Bhakti Kharatkar
·Mar 7, 2022·

5 min read

Hey everyone, Let's get started to understand what are higher order functions. We will discuss about map, filter and reduce functions.

Map :

  • It is an higher order function, which means it takes function as an argument and executes it. It acts similar like for loop.
  • It iterates over the array and for each element it performs task that we assign to it.
  • for every element it returns some value.
  • Here callback function takes current element, index (index of the current element in the array) and array (on which the map was called) as parameters. Index and array are optional parameters.

let's understand map with an example.

suppose in an array const array = [5,10,11,23,1,45], every element should incremented by 2 then,


const array =  [5,10,11,23,1,45];
const result = array.map(item => item + 2);
console.log(result);

//here the output is
//[7, 12, 13, 25, 3, 47]

what if we want to increment elements present on even index only then,

const array =  [5,10,11,23,1,45];
const result = array.map((item,index)=> index % 2 === 0 ? item + 2 : item);
console.log(result);

//here the output is
// [7, 10, 13, 23, 3, 45]

So, here in this example we use index also.

Also, Let's consider this code,

const array =  [5,10,11,23,1,45];
const result = array.map((item,index)=> {if(index % 2 === 0) return item + 2 } );
console.log(result);
// here the output is 
// [7, undefined, 13, undefined, 3, undefined]

From above example, if no value is return for any element while mapping then result for that element will be undefined.

Filter :

  • As its name suggest, it filters out the elements from the array that we actually want.
  • It also takes function as an argument just like map.
  • It performs a test for every element in an array, the one which do not pass the test is discarded and vice versa. And in the end we get a new array.
  • Here callback function takes current element, index (index of the current element in the array) and array (on which the filter was called) as parameters. Index and array are optional parameters.

Consider the following example,

const array =  [5,10,11,20,100,43];
const result = array.filter((item)=> item % 5 === 0 );
console.log(result);

//here output is 
// [5, 10, 20, 100]

In the above example, only the numbers which were divisible by 5 were returned.

const array =  [6,12,11,21,102,43];
const result = array.filter((item)=> item % 5 === 0 );
console.log(result);

//here output is
// []

If no element passes the test, an empty array is returned.

Reduce :

  • It is an higher order function, which means it takes function as an argument and executes it.
  • It performs some execution for every element in an array and returns the single result for all.
  • It is useful when we want resultant result of all elements according to a condition or some operation we want to perform.
  • here the callback function takes four arguments, accumulator, currentValue, currentIndex , array and initialValue(if provided).
  • accumulator is a result of the previous call of callback function, currentValue is the current element of the array and currentIndex is its index.
  • here we provide initialValue also.

    let's see how does it works.

Consider the following example,

const array = [1,2,3,4,5,6,7,8,9,10];
const sum = (num1, num2) => num1 + num2;
const result = array.reduce(sum);
console.log(result);

// here the output is 
// 55

what does it actually looks behind the scenes,

const array = [1,2,3,4,5,6,7,8,9,10];

  1. acc = 1 , curr = 2 --> 1+ 2 --> 3 (result)
  2. acc = 3 (result of the previous call to callback function) , curr = 3 --> 3 + 3 --> 6
  3. acc = 6, curr = 4 --> 6+ 4 --> 10
  4. so on, and upto the last acc = 45 , curr = 10 --> 45 + 10 --> 55 is the result.

Here initialValue is taken as first element of an array, because no initialValue was passed.

what if we want result as an object in the above example, here the we pass initialValue as an object, let's see

const array = [1,2,5,10,3,15];
const check = (obj , num) => num % 5 === 0 ? {...obj, divisibleByFive : obj.divisibleByFive + num  } : {...obj, notDivisibleByFive : obj.notDivisibleByFive + num} ;
const result = array.reduce(check, { divisibleByFive : 0, notDivisibleByFive : 0 });
console.log(result);

// here the output is 
// {divisibleByFive: 30, notDivisibleByFive: 6}

here the execution takes place in the same way when no initialValue passed, the only difference is here isaccumulator will be assigned with initialValue and currentValue will start assigning from 1st element of the array. Do make sure that we pass initialValue which are reliable, for example in the below code.

const array = [70 ,1,2,5,10,3,15];
const findGreatestNum = (num1 , num2) => num1 > num2 ? num1 : num2;
const result = array.reduce(findGreatestNum, 100);
console.log(result);

// here output is
// 100

In the above code the output is 100, which is not even present in the array. So, initialValue is used where only it is needed.

Let's consider a last one example in which we will use all the three methods. so here we will increment even numbers by 5 and will add all of them to get final value. In an array const array = [1,2,3,4,5,6,7,8,9,10,11,12,13];

const array = [1,2,3,4,5,6,7,8,9,10,11,12,13]
const checkEvenOrNot = num => num % 2 === 0 ;
const incrementByFive = num => num + 5 ;
const sum  = (acc , curr) => acc + curr ;
const result = array.filter(checkEvenOrNot).map(incrementByFive).reduce(sum);
console.log(result);

// here output is 
// 72

Thanks for reading this blog, I hope you understand the concepts. feel free to share your feedback for this blog in the comments.

 
Share this