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}
// ]
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]
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]
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']
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π
Top comments (24)
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.
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?
You can chain
map
andfilter
in functional languages, like for exampleF#
because there is no intermediate value.That's a good point with a great code presentation. ππ»
Thanks π€
Glad you like it. Check out other articles from my profile you definitely like it. π€
Yes, of course, thank you π€
And I'm proud to follow you.
Thank you for the kind words. ππ»
It means a lot π€
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).
Ohh my bad π
I will make it clear in some time.
Thanks for your feeback.ππ»
Nice thumbnail!! ππ
haha, Thanks π
I would also like to know your feedback about this article.
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. π€
You're welcome π€
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
Thanks
I am glad you like it. π€
Performing map, then filter is 2 iterations of the list. Despite some small readability gains, the performance loss is just too great.
The cover π€£
Hope you also enjoyed the article π
Thanks
Glad you like it. π€