Map, Filter, and Reduce Methods in Javascript

  

JavaScript provides powerful array methods like map, filter, and reduce, enabling developers to manipulate and transform arrays efficiently. In this blog post, we will use practical examples to showcase these methods' versatility and utility.
  • Map Method: Transforming Data 
The map method transforms each element of an array and creates a new array with the transformed values.

Let's take a look at an example :
const arr = [5, 1, 3, 2, 6]

//convert to binary = [101, 1, 11, 10, 110 ]


const convertBinary = function(x){

   return x.toString(2)

}

const output = arr.map(convertBinary)


                   Or


const output = arr.map((x) => x.toString(2))

  
  • The Filter Method -

The filter method is used to create a new array containing elements that pass a certain condition or criteria. 


Let's take a look at an example :
const arr = [5, 1, 3, 2, 6]

//filter out all odd number = [5,1,3]


const allOdd = function(x){

return x%2

}

const output = arr.filter(allOdd)


               Or


const output = arr.filter((x) => x%2)


  • The Reduce Method -

The reduce method accumulates a single value from an array by applying a function to each element.


Let's take a look at an example :
const arr = [5, 1, 3, 2, 6]

//find Max number


function findMax(arr){

let max = 0;

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

if (arr[i] > max){

  max = arr[i]

}

}

return max;

}

findMax(arr)


                 Or


const output = arr.reduce(function(acc, curr){

if(curr > acc){

acc = curr

}

return acc;

}, 0)



//Let's take one more example


const users = [

{ Fname:Raj, Lname:Salvi, Age:22 },

{ Fname:Ayush, Lname:Palkar, Age:22 },

{ Fname:Amar, Lname:Palkar, Age:25 },

];


//List of full name


const fullName = users.map((x) => x.Fname + " " + x.Lname)

console.log(fullName)



//{ 22:2 , 25:1 }


const Output = user.reduce(function(acc, curr){

if(acc[curr.Age]){

acc[curr.Age] = ++acc[curr.Age]

}else {

acc[curr.Age] = 1

}

return acc;

}, {})

console.log(Output)



//Fname with age<25


const Output = user.filter((x) => x.Age < 25).map((x)=> x.Fname);

console.log(Output)

or

const Output = user.reduce(function(acc, curr){ if(curr.Age < 25){ acc.push(curr.Fname); } return acc; }, []) console.log(Output)


In this blog post, we've explored JavaScript's map, filter, and reduce methods. These methods are essential for data transformation, filtering, and aggregation, making them powerful tools for array manipulation in your web development projects. Understanding when and how to use these methods can greatly improve your JavaScript coding skills.


 

Comments

Popular posts from this blog

Higher-Order Functions - Exploring the Power of Higher-Order Functions in JavaScript

Mastering JavaScript - A Comprehensive Guide to JavaScript Development with all Javascript Topic