What is Map, Reduce, and Filter in JavaScript?
Tags: webdev, javascript, beginners, tutorial
Published: 2023-09-26 03:57:19


![Cover Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7jym4cjd6sq15230zudv.png)

Developers and beginners still seem confused about these three array methods irrespective of the articles on Medium, freeCodeCamp, or any other platform.

I decided to explain these methods once again in simple and precise language. I'm contributing and adding to the other great articles on this topic.

Let's start with the `map()` method.

## Map

First, the Map object, a key-pair-based data structure, is not the `map()` method. Both of them solve different problems. They are not related or the same. We address the former as an Object and the latter as a method (function).

The map method allows you to run a callback function on each element of an array without modifying the original array. It creates a new duplicate array and scans through each element like a standard loop.

It has three arguments. The first one represents a variable that will hold the current element of the repetition. The second one stores the index of the current element in the loop from the array. The third represents the original array.

For the example below, imagine a person sitting in a cafe in the midst of their journey, trying to decide on a new location. They found three cities across the world. Now, he collectively wants to place a pin on each destination.

```
const locations = ['New York', 'Paris', 'Mount Fuji', 'Mumbai'];

locations.map((location) => console.log(`${location}: Pin Placed`));
```

![Map Method Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gjbjvms801s8kwfxaivv.png)

We printed “Pin Placed” to the console for each location to indicate that those locations are the upcoming locations for their journey. We iterated through each element using the `map()` method and called the `log()` method on each element.

For each element inside the array, JS will invoke the callback function. You can use that element as a parameter for the data inside the callback function. The method only invokes the callback function when a value exists at a specific index or position.

We are not using any standard loop, like `forEach()`, because it modifies the original array. We cannot afford to alter the original datasets in specific paradigms and massive applications.

## Filter

Now, the traveller has a limit on the number of items they can carry based on the weight of those items. I created an array of elements with different weights. Any item above 2 KG should be removed.

Let us use the `filter()` method to get rid of those items and get a new array (or luggage) that only contains items below 2 KG. Since all these Array methods return a new array, we might store them somewhere for later use unless you use `console.log()`, which immediately prints the results.

```
const weights = [1.3, 1.8, 1.5, 2.2, 2.5, 3.5];

const allowedItems = weights.filter((weight) => weight < 2);

console.log(allowedItems);
```

![Filter Output Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/falb6ybq646q7jaovlmt.png)

Any item above 2 KG was removed by the `filter()` method. We stored the new array in a new variable and printed it to the console. I directly gave the criteria for filtering those elements in the callback function. So, JS gave a condition to each item, and items below 2KG passed the test and moved to the allowedItems array.

Based on a specific condition, the `filter()` method removes the elements that fail to meet the criteria. Even the parameters are the same as the `map()` method.

## Reduce

I cannot figure out the total of these weights in my mind. I am bad at mathematics. I want to reduce those unsolicited weight numbers to a number representing the total weight.

```
const reducedNum = allowedItems.reduce((acc, item) => acc + item, 0);

console.log(reducedNum);
```

![Reduce Output Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nojnzv41tp4wo0o0iopy.png)

The `reduce()` method has an accumulator that maintains a unanimous count through each array element and keeps adding new values. 

We use `reduce()` to combine multiple elements, or mainly numbers. In our example, we used the allowedItems array from the previous `filter()` explanation and called the `reduce()` method on it.

This method takes two extra parameters. Those parameters are an accumulator and a default value. We must mention the accumulator as the first parameter in the parenthesis. Otherwise, it will consider any other variable at the first position as the accumulator. I name my accumulator variables as `acc`.

In the callback function, we add the weight of each item to the value currently present in the accumulator. The default or starting value of the accumulator comes outside the callback function as a parameter for the `reduce()` method. Usually, the default value remains 0, but this may differ based on the problem we are solving.

In the real world, parents are an example of an array that gets reduced to a final value. How? Well, their children. The kids are a combination and an entire version of their parents.

## Summary

The `map()` method allows you to go through each array element and perform a specific operation on each element with a callback function. 

We avoid using the `forEach()` loop precisely because the `map()` method does not modify the original array. Mostly, we do not want to change the original dataset.

The `reduce()` method allows you to combine elements of an array in a single number represented by the accumulator with a default value. You are reducing the entire array into a single number. 

Lastly, the `filter()` method allows you to choose specific elements from the original array and create a shallow copy of the elements that match a certain condition or criteria.

---

By the way, I am writing a book called [CrackJS](https://crackjs.com), which is based on and covers the fundamentals of JavaScript. If you want to learn more about JS, follow me on this journey of writing this book with these articles trying to help developers worldwide.

If you want to contribute, comment with your opinion and if I should change anything. I am also available via E-mail at hello@afankhan.com. Otherwise, Twitter (X) is the easiest way to reach out - @justmrkhan.