JavaScript Array Methods map(),filter(),reduce()

mrityunjaypalled

Mrityunjay-Palled

Posted on September 16, 2022

JavaScript Array Methods map(),filter(),reduce()

Map,Filter,Reduce are the most important and widely used array methods in JavaScript. let's take a look at them one by one.

map():It takes the array as the input, and returns a new array by applying a specific function on each individual array element. It does not modify the original array

syntax for map():

      array.map((ele,index,arr)=>{
          //ele->current element of the array
          //index->index of the current element
          //arr->entire array itself
      })
Enter fullscreen mode Exit fullscreen mode

In most of the cases only element is passed and other parameters are ignored. But they can be used as per the need

Example for map():

Image_description

In the above example each individual element of the array are multiplied by 10 and new array is returned

filter():It takes the array as the input, and applies the given condition on each individual element .The elements which satisfies the underlying condition are moved to the new array and remaining elements which does not satisfies the condition are filtered out. It does not modifies the original array

Syntax for filter():

     array.filter((ele,index,arr)=>{
         //ele->current element of the array
         //index->index of the current element
         //arr->entire array itself
     })
Enter fullscreen mode Exit fullscreen mode

like map in filter also only element is passed as parameter in most of the cases,and other two parameters are generally ignored

Example for filter():

Image_description

In the above example filter method returns the new array containing the elements the which are greater than 3

reduce():It will take array as a input, and returns the single
value by applying the give reducer function on each element of the array. It does not modifies the original array

Syntax for reduce():

       array.reduce((accumulator,ele,index,arr)=>{
         //accumulator->used to store the the value of 
                        previous iteration
         //ele->current element of the array
         //index->index of the current element
         //arr->entire array itself
         //value->initial value for accumulator
      },value)
Enter fullscreen mode Exit fullscreen mode

In most of the cases only accumulator and element are passed and other parameters are ignored

Example for reduce():

Image_description

In the above example after applying the reducer function it returns a single value that is 32, which is the sum of the individual array elements

💖 💪 🙅 🚩
mrityunjaypalled
Mrityunjay-Palled

Posted on September 16, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related