Javascript map vs filter performance

Javascript map vs filter performance

Javascript map vs filter performance

Nehal Mahida

Posted on Oct 27, 2021 • Updated on Nov 18, 2021

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!!

Which is faster map or filter?

map() method works faster or a . reduce() method works faster. I will run the above test 100 times and record the number of test winds each method has. With the plan above, Let's create a function that implements the .

Is Javascript filter slow?

To our surprise, for-loops are much faster than the Array. filter method. To be precise, the Filter method is 77% slower than for loop.

Is Javascript map faster than for loop?

map() works way faster than for loop. Considering the same code above when run in this ide.

Is filter faster than forEach Javascript?

Methods like map() and filter() are about twice as fast as using forEach() and pushing to a new array to do the same thing.