map() vs filter() vs forEach() vs reduce()

Table of Contents

map()

Syntax - 
array.map(function(eachElement,index ,arr) , thisValue)
  • Map returns an entirely new array without mutating the old array
//Iterating map on array

let arr = [1, 2, 3, 4, 5];

let output = arr.map((a, i) => {
  return arr[i] * 2;
});
console.log(output);  //new array 
console.log(arr);  //old array

Output - 
Array(5) [2, 4, 6, 8, 10 ]
Array(5) [1, 2, 3, 4, 5 ]


//Iterating map over array of objects

let arr = [
  { id: 1, name: "himanshu" },
  { id: 2, name: "shekhar" },
  { id: 3, name: "rohan" },
  { id: 4, name: "anjali" },
  { id: 5, name: "john" },
];

arr.map((each) => {
  console.log(each.name);
});

  • map chaining ability
//Multiply each element by 4 and then display only those eleemnt which are greater than 4

//Step 1 - use map() to iterate through each element and mutiply each element by 4
//Step 2 - use filter() to show only those elelment hich are greater than 4

let arr = [1, 2, 3, 4, 5];

let output = arr
  .map((a, i) => {
    return arr[i] * 2;
  })
  .filter((out) => {
    return out > 4;
  });

console.log(output);
console.log(arr);

Output - 
Array(3) [ 6, 8, 10 ]
Array(5) [ 1, 2, 3, 4, 5 ]

Watch video instead

  • Map return boolean value if any condition is passed. Check below example . [filter() over map()]
//Return thse elemen which are greate than 2

let arr = [1, 2, 3, 4, 5];

let output = arr.map((a, i) => {
  return a > 2;
});

console.log("new array : ", output);
console.log("old array : ", arr);

Output - 
new array :  Array(5) [ false, false, true, true, true ]
old array :  Array(5) [ 1, 2, 3, 4, 5 ]

Correct way (use filter() instead of map()) - 

let arr = [1, 2, 3, 4, 5];

let output = arr.filter((a, i) => {
  return a > 2;
});

console.log("new array : ", output);
console.log("old array : ", arr);

Output - 
new array : Array(3) [ 3, 4, 5 ]
old array :  Array(5) [ 1, 2, 3, 4, 5 ]

Using map() for API call

While working in react, you will realize the main job of a map is to play with API. Map and filter is going to be your best friend while dealing with API’s.

//Show only those github user, whose id is greater than 40

let output = async () => {
  let data = await fetch("https://api.github.com/users"); 
  let response = await data.json();  
  return response;
};

output()
  .then((r) => {
    r.map((eachData) => {
      if (eachData.id > 40) {
        console.log(eachData);
      }
    });
  })
  .catch((err) => {
    console.log(err);
  });

forEach()

  • forEach() does not mutate the old array and returns undefined
let arr = [1, 2, 3, 4, 5];

let output = arr.forEach((a, i) => {
  return arr[i] * 2;
});
//   .filter((out) => {
//     return out * 2;
//   });

console.log(output);
console.log(arr);

Output -
undefined index.js:12:9
Array(5) [ 1, 2, 3, 4, 5 ] 
  • forEach does not support chaining ability
let arr = [1, 2, 3, 4, 5];

let output = arr
  .forEach((a, i) => {
    return arr[i] * 2;
  })
  .filter((out) => {
    return out * 2;
  });

console.log(output);
console.log(arr);

Output - 
Uncaught TypeError: arr.forEach(...) is undefined

filter()

  • it’s similar to map, the only difference is that it return only those elements which have passed the criteria
  • filter doesn’t mutate the older array, It returns a new array.


let arr = [1, 2, 3, 4, 5];

let output = arr.filter((a, i) => {
  return a > 2;
});

console.log("new array : ", output);
console.log("old array : ", arr);


Output - 
Array(3) [ 3, 4, 5 ]
Array(5) [ 1, 2, 3, 4, 5 ]
  • Unlike map(), you cannot perform any action on each element with the help of a filter. [map() over filter()]
//Multiply each element by 2

let arr = [1, 2, 3, 4, 5];
let output = arr.filter((a, i) => {
  return a * 2;
});

console.log("new array : ", output);
console.log("old array : ", arr);

Output - 
new array :  
Array(5) [ 1, 2, 3, 4, 5 ]

old array :  
Array(5) [ 1, 2, 3, 4, 5 ]


Correct Way (use map()) instead of filer()) - >
let arr = [1, 2, 3, 4, 5];
let output = arr.map((a, i) => {
  return a * 2;
});

console.log("new array : ", output);
console.log("old array : ", arr);

Output - 
new array :  Array(5) [ 2, 4, 6, 8, 10 ]
old array :  Array(5) [ 1, 2, 3, 4, 5 ]

reduce()

A reduce function, as the name suggests returns a reduced result i.e a single value.

Synatx : 
array.reduce(function(initialValue/previously returned value/accumulated Value, currentValue, currentIndex, arr), initialValue)
//Find sum of the the elements in the array

let arr = [1, 2, 3, 4, 5];

let output = arr.reduce((a1, a2, i, arr) => {
  console.log(i);
  return a1 + a2;
});
console.log(output); 

Dry Run - 
// Working -
// assining values:
//   a1 = 1 (initial value)
//   a2 = 2(current value)

// loop 1:
//   i = 1
//   a1 = 1 + 2 = 3 (previously returned value)
//   a2 = 3

// loop 2:
// i = 2
// a1 = 3 + 3 = 6
// a2: 4

// loop 3:
// i = 3
// a1 = 6 + 4 = 10
// a2 = 5

// loop4:
// i = 4
// a1 = 10+ 5 = 15

// loop ends

   

Hope you found the article helpful. Thank you for reading.

Help Others

Leave a Reply

Your email address will not be published. Required fields are marked *