Akhilesh
Harsh Singh

Harsh Singh

Map, Filter, and Reduce in JavaScript under 5 minutes

Akhilesh's photo
Akhilesh
ยทNov 20, 2021ยท

4 min read

Map, Filter, and Reduce in JavaScript under 5 minutes

Introduction

Map, Filter and Reduce are Array Methods that are used for iterating over an array and returning value/array. It returns a new Array and it doesn't change the original Array. These methods are also very important in React JS which is a very popular JavaScript Library and using these methods also follows the functional programming paradigm.

So now let's look at them one by one,

Map

Map returns a new array which contains the result of applying the transformation on all the elements of the original array.

Syntax:

const returnedArray = array.map( Callback Function );

Callback function is a function that is passed as an argument in another function and later called inside that function.

The callback function passes the current element, index of the current element, and array as arguments.

This is what a callback function might look like:

const returnedArray = array.map((currentElement, index, array)=>{
    // return statement
})

let's look at simple example to understand the Map method:

//Sample Data
const sampleValues=[5,8,9,3,6];

// Here Map methods returns an array with 2 multiplied with all individual element
const multBy2=sampleValues.map((current, index, arr)=>{
    return 2*current;
})
console.log(multBy2);
//Console output:
//[object Array] (5)
//[10,16,18,6,12]

This is how the same problem will be solved using for loops

//Sample Data
const sampleValues=[5,8,9,3,6];

// declaring a new array to store the result
const returnedValue=[];
for(let value of sampleValues){
    returnedValue.push(value*2);
}
console.log(returnedValue);
//Console output:
//[object Array] (5)
//[10,16,18,6,12]

Filter

Filter returns a new array that only contains the elements that pass the specified condition.

Syntax:

const returnedArray = array.filter( Callback Function );

Filter can also pass the current element, index of the element, and the whole array as arguments in the callback function.

In filter with each iteration, we return a boolean value and based on that boolean value the array is formed.

let's use the same data and see how the filter works

//Sample Data
const sampleValues=[5,8,9,3,6];

// Filter returns the elements that are greater than 5
const greaterThan5=sampleValues.filter((curr)=>curr>5);
//Let's dry run 
//for i:0 curr=5  (curr>5) this returns false so it is discarded 
//for i:1 curr=8  (curr>5) this returns true so it is accepted
//for i:2 curr=9  (curr>5) this returns true so it is accepted
//for i:3 curr=3  (curr>5) this returns false so it is discarded 
//for i:4 curr=6  (curr>5) this returns true so it is accepted
console.log(greaterThan5);
//Console output:
//(3) [8, 9, 6]

How this example can be solved without the use of filter

//Sample Data
const sampleValues=[5,8,9,3,6];

// declaring a new array to store the result
const greaterThan5=[];
for(let value of sampleValues){
    if(value>5){
        greaterThan5.push(value);
    }
}
console.log(greaterThan5);
//Console output:
//(3) [8, 9, 6]

Reduce

Reduce as its name says reduces all the array elements down to one single value.

Syntax:

const returnedArray = array.reduce( Callback Function, accumulator initial value );

Reduce takes in two value the first one is Callback function and the other one is initial value of the accumulator.

In callback function extra accumulator is also passed along with the current element, index, and the whole array as arguments.

The Accumulator is a value that is kept from the previous callback function and the value of the accumulator is then passed as a result.

Let's see how reduce works by calculating sum of an array

//Sample data
const sampleData=[5,3,7,2,4,5];

//Reduce method returns 
const sum=sampleData.reduce((acc,curr)=>acc+curr,0);
//Let's dry run 
//for i:0 curr=5  acc=0   return value:5
//for i:1 curr=3  acc=5   return value:8
//for i:2 curr=7  acc=8   return value:15
//for i:3 curr=2  acc=15  return value:17
//for i:4 curr=4  acc=17  return value:21
//for i:5 curr=5  acc=21  return value:26
console.log(sum);
//Console Output:
//26

How this example can be solved without the use of reduce

//Sample data
const sampleData=[5,3,7,2,4,5];

//Reduce method returns 
let sum=0;
for(let value of sampleData){
    sum+=value;
}
console.log(sum);
//Console Output:
//26

Chaining of Array methods

Chaining means that attaching the Array methods one after another and creating a pipeline so that result of one method is passed into another method and so on...

Let's look at an example to understand chaining. In the transactions array, we are representing (+) as deposits and (-) as withdrawals. So now we have to calculate the withdrawals using chaining of Array methods.

const transactions=[-500,1000,2200,-650,-200,300];

//Calculating withdrawals
const withdrawals=transactions
        .filter(curr=>curr<0)
        .map(curr=>-1*curr)
        .reduce((acc,curr)=>acc+curr,0);
console.log(withdrawals);

//Console Output:1350

Even though chaining is very powerful and makes our code shorter and concise we should try not to overuse it so that it doesn't degrade the performance.

๐Ÿ™Œ So this was all about the Map, Filter, and Reduce. Hope it helped you understand the concept better and make your journey of learning JavaScript better.

๐Ÿ™ Thank you for reading the article and if you liked it, do share.

๐Ÿ™‹โ€โ™‚๏ธ Connect with me on Twitter.

ย 
Share this