filter, map and reduce in JS. When and Where to use??
Tags: javascript, webdev, beginners, programming
Published: 2021-10-27 05:06:48

### 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...
```js
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. 👇🏻

```js
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

```js
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.
```js
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.☕ 
<a href="https://www.buymeacoffee.com/nehalmahida"><img src="https://img.buymeacoffee.com/button-api/?text=Buy me a coffee&emoji=&slug=nehalmahida&button_colour=FFDD00&font_colour=000000&font_family=Cookie&outline_colour=000000&coffee_colour=ffffff"></a>


**Check out my other articles on DEV Community👇**

1. [Async/Await with easy to understand examples.](https://dev.to/nehal_mahida/asyncawait-with-easy-to-understand-examples-2221)
2. [How not to update states in React!!](https://dev.to/nehal_mahida/how-not-to-update-states-in-react-33om)