Sitemap

JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Using .map(), .filter() and .reduce() properly 👩🏽‍💻

5 min readDec 26, 2019

--

Map, reduce, and filter are all array methods in JavaScript. Each one will iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function. In this article, you will learn why and how to use each one.

Take note that this article most likely applies to whatever other programming language you might be using, as these are concepts that exist in many other languages

.map()

.map()function simply help you to perform a set of statements with every value in the iterable and return the modified value. For example if you have an array of people objects and you want to get their rent multiplied by 2. The typical way to do it with a foreach would be;

let people = [
{ id: 101, name: ‘Michelle’, rent:1200 },
{ id: 124, destination: ‘Bob’, rent:2400 },
{ id: 151, destination: ‘Paul’, rent:500 },
{ id: 171, destination: ‘Peter’, rent:3899 }
]
let newArray =[];people.forEach(person => {
newArray.push(person.rent * 2);
});
console.log(newArray)
//[2400, 4800, 1000, 7798]

There are multiple ways of achieve this. You might want to do it by creating an empty array, then using .forEach(), .for(...of), or a simple .for() to meet your goal.

So with the .map() function you can simply perform the same task as shown below.

const rentArray = people.map(person=>person.rent *2);console.log(rentArray)
//[2400, 4800, 1000, 7798]

Person is the variable used to access each and every element in the array. The statement after the arrow => is the body of our callback. Since the body has only one statement, we can omit the curly braces as well as the return keyword. So basically the above code is as same as the below.

let rentArray = people.map(person => {
return person.rent * 2;
});

So how does .map() work? Basically is takes 2 arguments, a callback and an optional context (will be considered as this in the callback) which I did not use in the previous example. The callback runs for each value in the array and returns each new value in the resulting array.

.filter()

.filter()function works as the name suggests. If you have an array, but you want only some of the elements in it? That’s where .filter() comes in. For example if you have an array of shipments with shipment ID and shipment destination and you want an array of shipments only headed to USA, the typical way of doing it would be;

let shipments=[
{ id: 101, destination: ‘USA’ },
{ id: 124, destination: ‘UK’ },
{ id: 151, destination: ‘UAE’ },
{ id: 171, destination: ‘USA’ },
{ id: 201, destination: ‘UK’ },
]

let newShipments = [];
shipments.forEach(shipment => {
if (shipment.destination == "USA") {
newShipments.push(shipment);
}
});
console.log(newShipments)
//[{id:101,destination:"USA"},{ id:171, destination:"USA"}]

So with the .filter()function you can simply perform the same task as shown below.

const newShipment = 
shipments.filter(shipment=> shipment.destination =='USA');
console.log(newShipment)
//[{id:101,destination:"USA"},{ id:171, destination:"USA"}]

Basically, if the callback function returns true, the current element will be in the resulting array. If it returns false, it won’t be.filter()builds a new array and never changes/mutates the old one, it just iterates over the old array.

reduce()

The .reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value. Just like .map(), .reduce() also runs a callback for each element of an array. What’s different here is that reduce passes the result of this callback (the accumulator) from one array element to the other.

The accumulator can be pretty much anything (integer, string, object, etc.) and must be instantiated or passed when calling .reduce().

For example say you have an array of integers and you want to get the sum of them.

const numbers = [ 2, 4, 6, 8, 10 ];numbers.forEach(number => sum += number);console.log(sum)
//30

We can perform this using .reduce();

const sum = numbers.reduce((acc, number) => acc + number, 0);console.log(sum)
//30

Notice that I’ve set the starting value as 0. I could have also used an existing variable if necessary. After running the callback for each element of the array, reduce will return the final value of our accumulator (in our case: 30).

Let’s combine .map(), .filter(), .reduce()

Let’s take a simple example. We have a group of students as follows.

const students = [
{
id: 5,
name: “Perone Skywalker”,
average: 78.9,
major: ‘Physics’,
},
{
id: 82,
name: “Micheal Wren”,
average: 73,
major: ‘Biology’,
},
{
id: 22,
name: “Zeb De Leone”,
average: 59,
major: ‘Physics’,
},
{
id: 15,
name: “Chidi Bridger”,
average: 73,
major: ‘Physics’,
},
{
id: 11,
name: “Caleb Canop”,
average: 33,
major: ‘Chemistry’,
},
{
id: 47,
name: “Neo Plims”,
average: 79,
major: ‘Biology’,
}
];

Now the goal is to get the total average of students who follow physics.

First we need to filter out students who follow physics.

const physicsStudents = students.filter( student=>student.major ==’Physics’);console.log(physicsStudents)
// [{...}, {...}, {...}] (Perone, Zeb and Chidi)

So we have an array of 3 students who follow physics. Now we have to get the average of these students. We can use .map() for that.

const average = physicsStudents.map(student => student.average);console.log(average);
//[ 78.9, 59, 73]

Now we can .reduce() and get the total.

const totalAverage = average.reduce((acc, score) =>{
return acc + score;
}, 0);
console.log(totalAverage);
//210.9

Now we can do this once.

const totalAverage = students
.filter(student => student.major ==”Physics”)
.map(student =>student.average)
.reduce((acc, score) => acc + score, 0);
console.log(totalAverage)
//210.9

Aaaaaaaand it’s done! 👊🏼

Try to replace some of your for loops with .map(), .reduce(), .filter() where it seems to fit. As you can see a large number of code lines can be reduced using these functions.

Hope I made the functions quite understandable.. 🤟🏽

Keep coding! ❤️👩🏽‍💻

Press enter or click to view image in full size
Image

--

--

JavaScript in Plain English
JavaScript in Plain English

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Sasanka Kudagoda
Sasanka Kudagoda

Written by Sasanka Kudagoda

Associate Technical Lead | Tech enthusiastic | IoT

Responses (1)