DEV Community

Cover image for Map(), Filter() and Reduce()
Deepayan Mukherjee
Deepayan Mukherjee

Posted on

Map(), Filter() and Reduce()

In this blog we will be discussing about some higher order Array methods which will be of immense use while working on any project and will up your vanilla JavaScript game.

Map:

map() is an array method that is used to iterate over an array and return a new array with the results of the function provided inside it

Key Points:

  • map() takes in a callback/function
  • map() always returns a new array be it a empty array
  • Does not change the size of array(unlike filter)
  • Always uses values from original array when making new one, but you don't have to use them if you don't want to but you will always have access to them

Now, we have an array of objects people where each object has a id, name, age and job

const people = [
  {
    id: 1,
    name: 'susan smith',
    age: 24,
    job: 'web developer',
  },
  {
    id: 2,
    name: 'anna johnson',
    age: 21,
    job: 'web designer',
  },
  {
    id: 3,
    name: 'peter jones',
    age: 32,
    job: 'intern',
  },
  {
    id: 4,
    name: 'bill anderson',
    age: 27,
    job: 'web developer',
  },
]
Enter fullscreen mode Exit fullscreen mode

Example 1:

We want to iterate over people and only print the names

const names = people.map((person)=>{
   return person.name;
})

console.log(names);  //returns ["susan smith", "anna johnson", "peter jones", "bill anderson"]
Enter fullscreen mode Exit fullscreen mode
  • We make a names array to store our results
  • We take an iterator named person to iterate over each element of people using map()
  • Within the arrow function we return the name of every object by accessing each object one at a time using person iterator
  • We then print the result array names

Example 2:

We want to iterate over people and return the name, age and job as an object

const infos = people.map((person)=>{
   return {
            firstName : person.name,
            age : person.age,
            position : person.job
           };
})

console.log(infos);  /*returns [{
  age: 24,
  firstName: "susan smith",
  position: "web developer"
}, {
  age: 21,
  firstName: "anna johnson",
  position: "web designer"
}, {
  age: 32,
  firstName: "peter jones",
  position: "intern"
}, {
  age: 27,
  firstName: "bill anderson",
  position: "web developer"
}]*/
Enter fullscreen mode Exit fullscreen mode
  • We make a infos array to store our results
  • We take an iterator named person to iterate over each element of people using map()
  • Within the arrow function we return the name, age and job as an object, of every object by iterating each object with person iterator
  • We then print the result array infos

Filter:

As the name suggests filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback function returns a value that is true

Key Points:

  • filter() takes in a parameter which is a callback/function
  • filter() always returns a new array be it a empty array
  • Changes the size of array as it returns an item only if the callback function returns true
  • If none of the item in the array satisfies the given condition then filter will return an empty array but if all the items satisfies the condition then all items in array will be returned

We will again take the same array people to understand how filter works

const people = [
  {
    id: 1,
    name: 'susan smith',
    age: 24,
    job: 'web developer',
  },
  {
    id: 2,
    name: 'anna johnson',
    age: 21,
    job: 'web designer',
  },
  {
    id: 3,
    name: 'peter jones',
    age: 32,
    job: 'intern',
  },
  {
    id: 4,
    name: 'bill anderson',
    age: 27,
    job: 'web developer',
  },
]
Enter fullscreen mode Exit fullscreen mode

Example:

We want to iterate over people and only print the detail of employees having job as web developer

const webDevelopers = people.filter((person)=>{
   if(person.job == 'web developer'){
      return person;
   }
})

console.log(webDevelopers);  /*returns [{
  age: 24,
  id: 1,
  job: "web developer",
  name: "susan smith"
}, {
  age: 27,
  id: 4,
  job: "web developer",
  name: "bill anderson"
}]*/
Enter fullscreen mode Exit fullscreen mode
  • We make a webDevelopers array to store our results
  • We take an iterator named person to iterate over each element of people using filter()
  • Within the arrow function we return the items that satisifies the condition which here is job being web developer
  • We then print the result array webDevelopers

Reduce:

The reduce() method reduces the array to a single value.It does not work for array elements without any value

Key Points:

  • reduce() takes in a callback/function
  • reduce() reduces our array and returns a single value which can be anything(number, array, object)
  • The callback function takes in 2 parameters :
    • First parameter - total of all calculations('accumulator')
    • Second parameter - iterator('current')

Now the parameters can be named anything you want but a common practice is to name them accumulator and current

We will again take the same array people with an added attribute salary to understand how reduce() works

const people = [
  {
    id: 1,
    name: 'susan smith',
    age: 24,
    job: 'web developer',
    salary: 500,
  },
  {
    id: 2,
    name: 'anna johnson',
    age: 21,
    job: 'web designer',
    salary: 300,
  },
  {
    id: 3,
    name: 'peter jones',
    age: 32,
    job: 'intern',
    salary: 100,
  },
  {
    id: 4,
    name: 'bill anderson',
    age: 27,
    job: 'web developer',
    salary: 500,
  },
]
Enter fullscreen mode Exit fullscreen mode

Example:

We want to iterate over people and print the total amount of salary of all the employees

const totalSalary= people.reduce((acc,curr)=>{
  acc += curr.salary;
  return acc;
},0)

console.log(totalSalary);//returns 1400(sum of salaries)//
Enter fullscreen mode Exit fullscreen mode
  • We make a totalSalary variable to store our results
  • We take an iterator named curr to iterate over each element of people and an accumulator acc to store the sum of salaries
  • Within the arrow function we return acc that has the total sum of salary of all the employees
  • We then print the result totalSalary

Thanks for reading!

Top comments (0)