DEV Community

Cover image for filter, map and reduce in JS. When and Where to use??
Nehal Mahida
Nehal Mahida

Posted on • Updated on

filter, map and reduce in JS. When and Where to use??

Introduction

In this article, We will take a look at the most used javascript methods for array transformations: filter(), map() and reduce().We will also take a look at in which condition these methods should be used.

Array.filter()

As the name suggests, the filter method is used to filter the elements from an array based on a given condition.

Elements for which the condition is true will be filtered and added in a new array all other will be discarded. At last, the filter method will return a brand new array.

Syntax

Array.filter((element, index, array) => { ... } )

We can have three arguments in a filter: the current element, index and the array itself. The callback function will have our condition to filter elements (You can make the condition as complex as you want).

Let's take an example to understand the filter method.

Suppose you are calling an API that returns a list of users having some details. You want to filter this list based on the age of individual users.

Let's code...

const users = [
  {
    name: "Van Batchelder",
    city: "London",
    birthYear: 1998
  },
  {
    name: "Winter Rubino",
    city: "Madrid",
    birthYear: 1992
  },
  {
    name: "Yusuf Shea",
    city: "Paris",
    birthYear: 1990
  },
  {
    name: "Zion Shively",
    city: "Alabama",
    birthYear: 2002,
  }
];

const currentYear = new Date().getFullYear();
const filteredUsers = users.filter((user) => (currentYear - user.birthYear) > 25);

console.log(filteredUsers);
// [
//  {name: 'Winter Rubino', city: 'Madrid', birthYear: 1992},
//  {name: 'Yusuf Shea', city: 'Paris', birthYear: 1990}
// ]
Enter fullscreen mode Exit fullscreen mode

You may have noticed that the callback function returns the boolean value true or false. Based on this return value, the element is added or discarded into the new array.

That's what you need to know about the filter method. 😊

Array.map()

The map method is used to iterate over an array. In each iteration, it applies a callback function on the current array element and finally returns a completely new array.

Unlike a filter, a map does not discard any element instead it manipulates the value of elements. So you can't skip the element if you want. The new array will have the same length as the current.

Syntax

Arrays.map((element, index, array) => { ... })

Same as a filter, we can have three arguments in the map. Usually, we need an element value. πŸ™‚

Let's take an easy to understand example. Suppose you want to convert a list of bitcoin values to dollar values. 🀩

So one way is to use the for loop. Start from the zero index up to the length of an array. At each index assign the converted value to the new array at the same position. πŸ‘‡πŸ»

const bitcoinList = [1, 3, 5, 4, 2];
const dollarList = [];

const bitcoinValue = 62953.10; // It's not a constant check it later!! :)

for (let i=0; i<bitcoinList.length; i++) {
    dollarList[i] = bitcoinList[i]*bitcoinValue;
}

console.log(dollarList); // [62953.1, 188859.3, 314765.5, 251812.4, 125906.2]
Enter fullscreen mode Exit fullscreen mode

But that's what a map does...

Now see the below code that is written using a map

const bitcoinList = [1, 3, 5, 4, 2];

const bitcoinValue = 62,858.20; // It changed :(

const dollarList = bitcoinList.map((bitcoin) => bitcoin * bitcoinValue);

console.log(dollarList); // [62953.1, 188859.3, 314765.5, 251812.4, 125906.2]
Enter fullscreen mode Exit fullscreen mode

Here I have used arrow functions shortcut, but you can do some extra work before finally returning the modified element. You may have noticed that the callback function returns the modified element which is eventually added into the new array.

So here we are mapping the values of one array to another that's why this method is called map.

That's what you need to know about the map method. Feel free to add any extra information you know about the map method in the comment box. πŸ’¬

Array.reduce()

It is the least used array method (but trust me, an important one!) compared to filter and map. Maybe a reason is this method is hard to understand (But not after this article πŸ˜‰).

As the name suggests, reduce is used to reduce the array πŸ™„

Syntax

reduce((previous, current, index, array) => { ... }, initialValue)

Don't worry by looking at the syntax. 😊

After taking an example, you will get it clear.

The examples on the internet for Reduce are so simple that we can't relate them to a real-life problem. But here, I will share a real-life scenario I faced that directs me to use Reduce.

Let's take the same users array we used in the filter method. The task is I want the list of usernames having an age greater than 25.

In this array, you may have some users having birthYear as NULL or undefined. So here you need to use the filter method to remove users having invalid birthYear.

From the filtered array, you just want usernames so here you will use the map method to extract the usernames from the user object.

See, you need to use two methods to accomplish this task. but What if I tell you you can achieve the result using only one method and you know which method I am talking about πŸ˜‰

It's reduce.

Let's code.

const users = [
  {
    name: "Van Batchelder",
    city: "London",
    birthYear: 1998
  },
  {
    name: "Winter Rubino",
    city: "Madrid",
    birthYear: null
  },
  {
    name: "Yusuf Shea",
    city: "Paris",
    birthYear: 1990
  },
  {
    name: "Zion Shively",
    city: "Alabama",
    birthYear: 2002,
  }
];

const currentYear = new Date().getFullYear();

const userNames = users.reduce((filterUsers, user) => {
  if (user.birthYear && (currentYear - user.birthYear) > 25) {
    filterUsers.push(user.name);
  }
  return filterUsers;
}, []);

console.log(userNames);
// ['Yusuf Shea']
Enter fullscreen mode Exit fullscreen mode

Let's understand the code based on syntax. Here the filterUsers is our previous, user is our current and empty array ([]) is our initialValue from syntax. We don't need index and array in the callback function.

In the first iteration filterUsers be an empty array based on an initialValue given. In the function body, we put a condition that if a user has a birthYear and his/her age is greater than 25 then push it on filterUsers otherwise return filterUsers. Finally, our userNames is having a filtered and mapped list. 🀩

You may find this task can be solved using other approaches but trust me this is the best example I can give you to explain reduce 😎

In nutshell,

filter: When you need to remove some unwanted element from array.
map: Convert one array into another.
reduce: When you need to boils down the array.

Yes, that's it. Hope you enjoyed my article.
If you like this article like share and mark πŸ”– this article!

If you are on Twitter, give a follow, I share amazing resources to learn web development. πŸ™πŸ»

The feedbacks are appreciated. πŸ€—

πŸƒβ€β™‚οΈ Let's Connect πŸ‘‡

πŸ•Š Twitter : https://twitter.com/nehal_mahida (See you on Twitter πŸ˜ƒ)

πŸ‘¨β€πŸ’» Github: https://github.com/NehalMahida

Support πŸ€—

If you are enjoying my articles, consider supporting me with a coffee.β˜•

Check out my other articles on DEV CommunityπŸ‘‡

  1. Async/Await with easy to understand examples.
  2. How not to update states in React!!

Top comments (28)

Collapse
 
nehal_mahida profile image
Nehal Mahida

Definitely a good point πŸ‘πŸ»

Performance vs readability is a never-ending debate.

I intend how we can avoid two methods by just using reduce and explaining to the people how to use reduce syntactically!!

And yes, for loop is there to achieve all of these things.

Collapse
 
captainyossarian profile image
yossarian • Edited

You will get noticeable performance hit if your array has more than 1K elements. In worst case scenario you will iterate 2 times over 1K elements. Btw, what makes you think that reducer is not readable?

type User = {
  name: string;
  city: string;
  birthYear: number;
}
declare const users: User[]

const currentYear = new Date().getFullYear();

const olderThan25 = (user: User) =>
  user.birthYear && (currentYear - user.birthYear) > 25 ? [user] : []

const getName = ({ name }: User) => name

const userNames = users.reduce((acc, user) =>
  olderThan25(user)
    ? acc.concat(getName(user))
    : acc,
  [] as Array<User['name']>
);
Enter fullscreen mode Exit fullscreen mode

You can chain map and filter in functional languages, like for example F# because there is no intermediate value.

Collapse
 
nehal_mahida profile image
Nehal Mahida

That's a good point with a great code presentation. πŸ‘πŸ»

Collapse
 
miladtehrany profile image
Milad Tehrany

Thanks πŸ€—

Collapse
 
nehal_mahida profile image
Nehal Mahida

Glad you like it. Check out other articles from my profile you definitely like it. πŸ€—

Collapse
 
miladtehrany profile image
Milad Tehrany

Yes, of course, thank you πŸ€—
And I'm proud to follow you.

Thread Thread
 
nehal_mahida profile image
Nehal Mahida

Thank you for the kind words. πŸ™πŸ»

It means a lot πŸ€—

Collapse
 
ysiad profile image
Ysiad

Hi, thank you for this article ! I'm still learning and it helps to review basics. Just a little comment about the variables you use to illustrate the reduce fonction : in the code it's filterUser and in the article filterUsers, and the same goes with "user" and "users", I think it can be important for the understanding that the names remain consistent between the explanation and the code (well for me it's confusing when there's an extra or a missing "s" at the end sorry ahahah).

Collapse
 
nehal_mahida profile image
Nehal Mahida

Ohh my bad πŸ˜…

I will make it clear in some time.

Thanks for your feeback.πŸ™πŸ»

Collapse
 
anstroy profile image
Aus G

Nice thumbnail!! πŸ˜‚πŸ˜‚

Collapse
 
nehal_mahida profile image
Nehal Mahida

haha, Thanks πŸ˜…

I would also like to know your feedback about this article.

Collapse
 
anstroy profile image
Aus G

I liked the .reduce() method explanation, personally I have only used it a few times, but still is hard for me to understand what it does. You explained it pretty well, thanks for sharing. 🀘

Thread Thread
 
nehal_mahida profile image
Nehal Mahida

You're welcome πŸ€—

Collapse
 
maryamos1 profile image
MaryAmos1

The map(), reduce() and filter() are array functions that transform the array according to the applied function and return the updated array obsession spell with cotton balls

Collapse
 
sadid369 profile image
Sadid

Thanks

Collapse
 
nehal_mahida profile image
Nehal Mahida

I am glad you like it. πŸ€—

 
uuykay profile image
William Kuang

Performing map, then filter is 2 iterations of the list. Despite some small readability gains, the performance loss is just too great.

Collapse
 
siddharthshyniben profile image
Siddharth

The cover 🀣

Collapse
 
nehal_mahida profile image
Nehal Mahida

Hope you also enjoyed the article πŸ˜…

Collapse
 
amitkum66494760 profile image
Amit Yadav

Thanks

Collapse
 
nehal_mahida profile image
Nehal Mahida

Glad you like it. πŸ€—

Collapse
 
banyakinfoku profile image
banyakinfoku

what are you doing here

bit.ly/3BEbcZa

Collapse
 
topolanekmartin profile image
Martin Topolanek

Thanks! Finally get it what is reduce function about :)

Collapse
 
nehal_mahida profile image
Nehal Mahida

Purpose served πŸ€—