Unlocking the Power of Map, Filter, and Reduce in JavaScript
Tags: javascript, webdev, frontend
Published: 2024-03-18 20:44:52

Map, filter and reduce are commonly used in Frontend development. However, developers are often confused about their behaviour. Each array method map, filter and reduce returns a new array based on the result of the function. In this article, you will also learn the **power of the reduce method.**

## Map
The purpose of the `Map()` method in JavaScript is to transform each element of an array using a provided callback function and then return a new array containing the transformed elements.

```
const numbers=[2,3,4,5,6,7];

numbers.map(function(element, index, array){
    console.log('element',element, 'index',index,'array', array);
})
```
**Output**
```
element 2 index 0 array [ 2, 3, 4, 5, 6, 7 ]
element 3 index 1 array [ 2, 3, 4, 5, 6, 7 ]
element 4 index 2 array [ 2, 3, 4, 5, 6, 7 ]
element 5 index 3 array [ 2, 3, 4, 5, 6, 7 ]
element 6 index 4 array [ 2, 3, 4, 5, 6, 7 ]
element 7 index 5 array [ 2, 3, 4, 5, 6, 7 ]
```
**Are you afraid of seeing the syntax of the map? Don't worry. I'm here to explain you.**

Map takes 3 parameters **elements, index and array**. However,  you need only **element** to transform into a new array. Keep in mind that the word transformed. For example, Suppose I have an array containing 5 numbers (1 to 5). I want to double each element, but I could also triple them or perform other transformations. Here is an example below.

```
const numbers=[1,2,3,4,5];

const doubleIt= numbers.map((element)=>element*2);
console.log(doubleIt) //[ 2, 4, 6, 8, 10 ]
```
Remember the purpose of the array method transform each element of an array and return a new array containing the transformed elements. here numbers transformed in [2,4,6,8,10]. I hope now it is clear. 

### Apply Map
Now is the time to apply a **map** example for better understanding. Here is an example below

```
const students = [
    {id:1, name: 'Ahmed', age: 19, email: 'ahmed@gmail.com' },
    {id:2, name: 'Rahman', age: 23, email: 'rahman@gmail.com' },
    {id:3, name: 'Bablu', age: 22, email: 'bablu@gmail.com' },
    {id:4, name: 'Jakir', age: 21, email: 'jakir@gmail.com' },
    {id:5, name: 'Mahin', age: 17, email: 'mahin@gmail.com' },
];

```
From student array, **you want to display only the ID and email** of the student. How can you do that?

```
const studentIdAndEmail = students.map(student => {
    return { id: student.id, email: student.email };
});
console.log(studentIdAndEmail);
```
**Output:**

```
[
    { id: 1, email: 'ahmed@gmail.com' },
    { id: 2, email: 'rahman@gmail.com' },
    { id: 3, email: 'bablu@gmail.com' },
    { id: 4, email: 'jakir@gmail.com' },
    { id: 5, email: 'mahin@gmail.com' }
]
```

## Filter
The `Filter()` method checks each item in an array based on a condition set by a function. If this condition returns true, the element gets pushed to the output array. If the condition returns false, the element does not get pushed to the output array.

```
const numbers=[2,3,4,5,6,7];

const filteredNum= numbers.filter((element)=>element>4);
console.log(filteredNum);//[ 5, 6, 7 ]
```
Remember I  mentioned the `filter()` method which will check each in an array based on a condition. Pay attention to the word =**Condition**. In the above, you will see a condition applied if the array element is greater than 4 then it will return a new array. As a result, it returns  a `[5,6,7]`

### Apply Filter

Now is the time to apply a **filter** example for better understanding. Here is an example below.

```
const books = [
    { title: 'The Great Gatsby', genre: 'Fiction', publish: 1925, edition: 2004 },
    { title: 'To Kill a Mockingbird', genre: 'Fiction', publish: 1960, edition: 2006 },
    { title: '1984', genre: 'Science Fiction', publish: 1949, edition: 2003 },
    { title: 'The Catcher in the Rye', genre: 'Fiction', publish: 1951, edition: 2001 },
    { title: 'Pride and Prejudice', genre: 'Romance', publish: 1813, edition: 2005 },
    { title: 'The Hobbit', genre: 'Fantasy', publish: 1937, edition: 2012 },
    { title: 'The Da Vinci Code', genre: 'Thriller', publish: 2003, edition: 2018 },
    { title: 'Harry Potter and the Philosopher\'s Stone', genre: 'Fantasy', publish: 1997, edition: 2014 },
    { title: 'The Lord of the Rings', genre: 'Fantasy', publish: 1954, edition: 2001 },
];
```
From the books array you want to display a **book whose genre is "Thriller" and that was published after 2000.** How can you display it?

```
const filterBookData= books.filter((book)=>{
    return book.genre==='Thriller' && book.publish>=2000
})
console.log(filterBookData)
 
```
**Output**

```
 [
 {
    title: 'The Da Vinci Code',
    genre: 'Thriller',
    publish: 2003,
    edition: 2018
  }
]
```
## Reduce

The `reduce()` method may seem difficult at first. When you see the tutorials of the reduce method you often come across the same example repeatedly, which is summation. But **Reduce is more powerful than simple summation. it combines all elements of an array into a single value by applying a function repeatedly.**

Don't worry. Reduce is not that hard the way you think. Suppose you have a piggy bank and a bunch of coins scattered on your table. Each coin has a number written on it representing its value.

**Now, you want to find out the total value of all coins you have?**
So, you start picking up each coin, one by one, and you keep adding its value to the amount you've already collected in your piggy bank. The amount in your piggy bank keeps growing as you add more coins.

In this story:

- The piggy bank represents the **accumulator,** which keeps track of the total value collected so far.
- Each coin represents the **currentValue,** the individual value being added to the accumulator.
- By the end, the total amount in your piggy bank represents the final result returned by the `reduce()` method.

Based on this story I will give you a example so, that you will more clear about the topic.

```
const coins = [5, 10, 25, 50, 100]; 

const totalValue = coins.reduce((accumulator, currentValue) => {
   
    return accumulator + currentValue;
}, 0); // 0 is the initial value of the accumulator

console.log("Total value of coins:", totalValue); // Output: Total value of coins: 190

```

I have told you `reduce()` is more powerful than summation. Here is the example below. 

```
const names = [
    'Al-Amin',
    'Abdul',
    'Abu boklor',
    'Bijoy ',
    'Bisso',
    'Emran',
    'Fahad',
    'Fahim',
    'Hamim',
    'HM Rahman',
    'Hridoy Ahmed',
    'Jahid Mia',
    'Johir',
    'Md Al-Amin',
    'Md Rakib',

];

```
From this name array I want to display namesGroup like this

**Output:**
```
{
  A: [ 'Al-Amin', 'Abdul', 'Abu boklor' ],
  B: [ 'Bijoy ', 'Bisso' ],
  E: [ 'Emran' ],
  F: [ 'Fahad', 'Fahim' ],
  H: [ 'Hamim', 'HM Rahman', 'Hridoy Ahmed' ],
  J: [ 'Jahid Mia', 'Johir' ],
  M: [ 'Md Al-Amin', 'Md Rakib' ]
}
```
Here is code below: 

```
const namesGroup= names.reduce((acc, curr)=>{
    const firstLetter= curr[0].toUpperCase();
    if(firstLetter in acc){
        acc[firstLetter].push(curr)
    }
    else{
        acc[firstLetter] = [curr];
    }
    return acc;
}, {})
console.log(namesGroup)
```
## Summary
"JavaScript's array methods map, filter, and reduce are powerful tools for manipulating arrays efficiently.

- map() transforms each element of an array according to a given function, returning a new array of the transformed elements.
- filter() selects elements from an array based on a specified condition, returning a new array containing only those elements.
- reduce() applies a function to each element of an array, accumulating a single value.

These methods can greatly simplify array manipulation tasks, leading to cleaner and more expressive code. Understanding how and when to use them can significantly improve the efficiency and readability of JavaScript code."