The Talent500 Blog
How to Use Javascript’s Map, Filter and Reduce methods 1

How to Use Javascript’s Map, Filter and Reduce methods

As a front-end developer, you must know about JavaScript’s map(), filter(), and reduce() methods. So in this article, we will dive deep into these methods with real-world examples.

map() Method:

An overview of the map() method:

The map() method accepts a callback function once for each array element. And it returns a new array containing the results of the performed operation on all the original array elements.

It does not execute the function for an empty array and doesn’t change the original array either.

Syntax of the map() method:

arrayName.map(callBackFun) 

The callBackFun function is called for each item in the array, and its returned value will be added to the new array.

And this callBackFun function also accepts some arguments.

arrayName.map(function (item, index, array) {

  //Lines of code

});

item: The item is the current element of the array processed by the callback function.

index: The index argument is the index of the current item in the array.

array: The array on which the map() method is called(In the above syntax, array and arrayName are the same things)

Example of map() method:

Suppose we want to convert an array that contains dollars into Indian rupees (INR). In this case, we can easily convert it using the map() method, but it’s also converted using JavaScript loops, requiring some extra lines of code(See the next example).

const dollar = [10, 20, 30, 40, 50];

const dollarToInr = 80;

const inr = dollar.map(function (item) {

  return item * dollarToInr;

});

console.log(inr);

//[ 800, 1600, 2400, 3200,4000 ]

In the above example, we called the map() method on the dollar array, and this array accepts a callback function that receives only one item argument. The rest of the arguments are optional, so I omitted them.

And after calling the map() method on the dollar array, it constructs a new array, that is inr.

But as I said, we can also achieve this goal using JavaScript loops like the old ways, which will not be required in the map() method.

const dollar = [10, 20, 30, 40, 50];

const dollarToInr = 80;

let inr = [];

for (const item of dollar) {

  inr.push(item * dollarToInr);

}

console.log(inr);

//[ 800, 1600, 2400, 3200,4000 ]

In the above code snippet, I create an empty array and then push all items into the new array that is inr.

But on the other hand, we do not need to create an empty array and push all items into that array when we use the map( ) method.

filter( ) method

The filter( ) method returns an array that passes a particular condition provided by the callback function. If no element passes the condition, then it returns an empty array.

In short, we can say that the filter( ) method filters the element of the array based on the condition.

Syntax of the filter( ) method:

arrayName.filter(function (item, index, array) {

  //Lines of code.

});

It also accepts arguments the same as the map() method. The item is the current element of the array, an index is the current index of the array elements, and the array arguments are the actual array on which the filter() method was called.

Example

Suppose we want to filter all the names in the array, starting with the letter A. Then we can quickly achieve this goal using the filter() method. Let’s see how.

let user = [“Ajay”, “Sonu”, “Tanay”, “adarsh”];

let nameStartWithA = user.filter(function (item, index) {

  return item.startsWith(“A”) || item.startsWith(“a”);

});

console.log(nameStartWithA); // [ ‘Ajay’, ‘adarsh’ ]

In the above code snippet, I have called the filter( ) method on the user array that accepts a callback function, and the return statements return Boolean values(true or false).

If the return statement evaluates to true, then that particular element of the array will be passed the condition and stored in the new array.

But if the return statement evaluates to false, then that array element will not satisfy the condition, so they are not stored in the newly constructed array.

Remember, the callback function runs for each element of the array.

reduce() method:

The reduce( ) method is hard to understand the first time. That’s why I explain the old ways of school first using a loop. Then I promise you that it will be easy to understand the reduce( ) method.

Suppose we want a single value after adding all the array elements. Then we can easily achieve this goal using JavaScript loops.

const myArray = [10, 20, 30, 40, 50];

let total = 0;

for (let i = 0; i < myArray.length; i++) {

  total = total + myArray[i];

}

console.log(total); //150

In the above code, I have created a variable called total that holds the initialValue of 0. And all the array elements have been accommodated one by one in the total variable.

Similarly, we can also achieve this goal using the reduce( ) method. Let’s see how.

Overview of reduce( ) method:

The reduce( ) method executes a reducer(shorter) function on each array element and returns a single value as an output, and it does not execute the reducer function for an empty array.

Syntax

arrayName.reduce(function (total, item, index, array) {

  //Lines of code.

}, initialValue);

In the above code, I have called the reduce( ) method on an arrayName array that accepts two arguments: a reducer or shorter callback function and the initialValue.

The callback function also accepts some arguments:

total: It’s a result of the previous function call that is equal to the initialValue if provided, also known as an accumulator.

The next three arguments(item, index, and array) do the same as we discussed above.

initialValue: It’s a starting value used to initialize the value for the first time when the callback function is called.

Example

const myArray = [10, 20, 30, 40, 50];

const totalValue = myArray.reduce(function (total, item) {

  return total + item;

}, 500);

console.log(totalValue); //650

Here, the initialValue value will be 500, which is added to the array element for the first time.

Let’s see how it works behind the scenes.

In the 1st iteration:

initialValue = 500

total = 500 as well

item = 10

totalValue = 510

2nd iteration:

total = 510

item = 20

totalValue = 530

3rd iteration:

total = 530

item = 30

totalValue = 560

4th iteration:

total = 560

item = 40

totalValue = 600

5th iteration:

total = 600

item = 50

totalValue = 650

So the final output will be 650.

But if we want to calculate only the elements of the array, then we must need to put 0 as the initialValue.

let arrayName = [10, 20, 30, 40, 50];

const totalValue = arrayName.reduce(function (total, item) {

  return total + item;

}, 0);

console.log(totalValue); //150

In the above example, I’ve put 0 as the initialValue, but in this case, we can also omit 0. The result will be the same.

let arrayName = [10, 20, 30, 40, 50];

const totalValue = arrayName.reduce(function (total, item) {

  return total + item;

});

console.log(totalValue); //150

Wrap Up

The map( ) method maps each item from the original array and performs some operation, then returns a new array corresponding to the original array’s elements.

The filter( ) method filters the element from the original array based on the particular condition, then returns a new array.

And the reduce ( ) method condenses or shortens the original array’s elements into a single value. Keep in mind that it returns a single value but not an array.

 

5+
Ajay Yadav

Ajay Yadav

I am a frontend developer and am eager to deep dive into the technologies through my content.

Add comment