Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
map() in Javascript
3.
reduce() in Javascript
4.
filter() in Javascript
5.
Combining .map(), .reduce(), and .filter()
6.
Frequently Asked Questions
7.
Key takeaways
Last Updated: Mar 27, 2024

map(), filter(), reduce() in Javascript

Author Reet Maggo
1 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Javascript has several array methods to operate on and iterate over arrays to perform specific transformations and computations. These provide convenient methods for such operations and can be chained to work together efficiently. The map(), reduce() and filter() methods are some of such array functions that perform the given operation on arrays and return the updated arrays. This article will discuss how the three methods can be implemented individually and in a single line using suitable examples.

Also Read About, Javascript hasOwnProperty

map() in Javascript

.map() takes two arguments, a callback, along with some optional context. For each value, callback runs to return a new value in the resulting array, which is always the length of the original array itself.

The map function has several built-in functions for static and instance properties. Some significant built-in map functions are listed below:

  • Map.prototype.clear() to remove all the key-value pairs.
  • Map.prototype.size to return all the key-value pairs from the Map object.
  • Map.prototype.get(key) to return either the value associated with the key or undefined in case there isn’t any.
  • Map.prototype.set(key, value) to set values for keys in the Map object.

The list is over yet, there are tons of methods resides in the map() function. 

E.g. for map(): For an array with multiple objects, each representing an individual, we need a final array containing just the id of every individual.

Input

var council = [

  { id: 2100, name: 'President Jacqueline' },

  { id: 2114, name: 'Vice-president James' },

  { id: 3016, name: 'House-captain Otis' },

  { id: 4818, name: 'Prefect Finneas' }

];

Output [2100, 2114, 3016, 4818]

 

We could approach this from various methods. We can either create an empty array, and use .forEach(), .for(...of), or just a .for() to get the desired output.

Let us now have a look at these methods one by one:

Using .forEach():

var councilIds = [];
council.forEach(function (counc)
{
  // pushing each ID onto the additional created array
  councilIds.push(counc.id);
});

 

So if we use .forEach(), we need to create an empty array in advance. 

Using .map():

var councilIds = council.map(function (counc)
{
  return counc.id
});

 

Using arrow functions:

Arrow functions further helps us be more concise and require ES6 support, Babel or TypeScript.

const councilIds = council.map(counc => counc.id);
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

reduce() in Javascript

.reduce() runs a callback for every array element just like .map() does. The only difference is that reduce() passes the result of this accumulator from one array element to the other. Some built-in reduce() functions are:  Array.prototype.reduce(), and the reduceRight() method which are used to apply functions against accumulators from 1. Left to right and 2. Right to left respectively.

The accumulator either contains the initial value or the return value from the previous call. The accumulator could be any string, integer, object, etc. It is the net result of the function. The present value of the accumulator is simply the element that is being worked against. 

Accumulators must be passed when .reduce() is being called.

Consider the below picture to visualize the working of the accumulator: 

Source:Medium

 

Let us take another example:

Assume, we have an array of employees along with their years of work experience. We only want the total years of all employees’ work experience as the output.

Input

var employees = [

  {

    id: 111,

    name: "Chelsea Foster",

    years: 7,

  },

  {

    id: 102,

    name: "Aggie Sparling",

    years: 13,

  },

  {

    id: 123,

    name: "Timmy Matthews",

    years: 23,

  },

  {

    id: 119,

    name: "Emmet Foster",

    years: 22,

  }

];

Output 65

 

To get the total years of experience, we could straightforwardly use .reduce():

var totalYears = employees.reduce(function (accumulator, employee)
{
  return accumulator + employee.years;
}, 0);

 

The starting value is set here as 0. After the callback runs for every array element, reduce returns the final value of the accumulator, which is 65 in our case.

filter() in Javascript

Now, if we just want some of the elements in the array we have, we can use .filter().

Input

var members =

[

  {

    id: 111,

    name: "Chelsea Foster",

    position: "Intern",

  },

  {

    id: 102,

    name: "Aggie Sparling",

    position: "Employee",

  },

  {

    id: 123,

    name: "Timmy Matthews",

    position: "Intern",

  },

  {

    id: 66,

    name: "Emmet Foster",

    position: "Employee",

  }

];

 

Now, if we want one array for the interns and one for employees:

var interns = members.filter(function (members)
{
  return members.position === "Intern";
});
console.log(interns);

 

Output:

 

var employee = members.filter(function (members)
{
  return members.position === "Employee";
});
console.log(employee);

 

Output:

 

With arrow functions:

const interns = members.filter(member => member.faction === "Intern");
const employee = members.filter(member => member.faction === "Employee");

 

The current elements are in the resulting arrays if the callback is true. Otherwise, they are not included in the final array.

Also, see Recursion

Combining .map(), .reduce(), and .filter()

.map(), .reduce() and .filter() are all used on arrays. In fact, map and filter return arrays too, meaning we can chain these calls very conveniently. Here’s an example:

var members =
[
  {
    id: 111,
    name: "Chelsea Foster",
    workExp: 7,
    deptExp: 6,
    isPermanent: true,
  },
  {
    id: 102,
    name: "Aggie Sparling",
    workExp: 13,
    deptExp: 10,
    isPermanent: false,
  },
  {
    id: 123,
    name: "Timmy Matthews",
    workExp: 23,
    deptExp: 15,
    isPermanent: false,
  },
  {
    id: 66,
    name: "Emmet Foster",
    workExp: 22,
    deptExp: 9,
    isPermanent: true,
  },
  {
    id: 89,
    name: "Brent Dolan",
    workExp: 16,
    deptExp: 12,
    isPermanent: true,
  },
];

 

If we want the total score of permanent employees only, we will first filter out the non-permanent members:

var permMember = members.filter(function (member)
{
  return member.isPermanent;
});

 

Output:

[{...}, {...}, {...}] (Chelsea, Emmet, Brent)

 

Now that the resulting array has three elements, we want to create an array with the total score of each one of those:

var totalScore = permMember.map(function (totalYears)
{
  return totalYears.workExp + totalYears.deptExp;
});

 

Output:

[13, 31, 28]

 

Now add the total score of permanent employees:

var combinedTotalScore= totalScore.reduce(function (acc, total)
{
  return acc + total;
}, 0);

 

Output:

72

 

Now, combining these three and chaining them into one line:

var combinedTotalScore = members
  .filter(function (member)
  {
    return member.isForceUser;
  })
  .map(function (totalYears)
  {
    return totalYears.workExp + totalYears.deptExp;
  })
  .reduce(function (acc, total)
  {
    return acc + total;
  }, 0);

 

With arrow functions:

const combinedTotalScore = members
  .filter(member => member.isPermanent)
  .map(totalYears => totalYears.workExp + totalYears.deptExp)
  .reduce((acc, total) => acc + total, 0);

You can try it by yourself on an online JS editor.

Frequently Asked Questions

Q1. How are filter, map and reduce different?

Ans: .map() transforms every element in an array individually and creates a new array. filter() removes elements that are not required and creates a new array containing the ones needed. Finally, reduce() reduces all array elements into a single value.

 

Q2. What is the length of arrays made using .map() in javascript?

Ans: Since map() individually transforms all elements of an array to create a new array, the length of the new array is the same as that of the original one.

 

Q3. Does .filter() create new arrays of the same length as the previous one?

Ans: Filter removes the unrequired elements while creating a new array and only includes the ones necessary. Therefore, the length of the new array is usually lesser than that of the original one.

Refer to know about:   jquery ajax

Key takeaways

In this article, we learned about the map(), reduce(), and filter() methods and how we can combine them to make the code concise and efficient. We also used examples to get a better understanding of situations where such array methods could be used.

To clarify the concepts, implement the stated methods on your own and analyze the outputs.

Check out this problem - Search In Rotated Sorted Array

Read more, Access modifiers in java

You can go to Coding Ninjas Studio to try and solve more problems for practice. Share this blog with your friends if you found it helpful! Until then, All the best for your future endeavours, and Keep Coding.

Previous article
Rest parameters and Spread syntax
Next article
JavaScript scopes, closures
Live masterclass