Map, Reduce & Filter Functions in JavaScript

Map, Filter and Reduce are generally called as Higher-Order Functions in javascript. All the array methods like Map, Reduce, and Filter is used for iterating over an array and performing computation or transformation. Each of the array methods like map, reduce, and the filter returns a new array based on the result of the function. In this article, we will generally focus on why they are used and how to use them in day-to-day life.

Map

The map() method is used for creating a new array from an array and applying a function to each one of the elements of an array.

Syntax

Map Syntax

In the callback generally, the array element is required. Some action is performed to the value and the new value is returned.

Let us understand it with the help of an example:

Example:

Map Example

Output

Map Output

Filter

A filter method is used to take each element in an array and it applies a conditional statement against it. If the conditional statement returns true, then the elements get pushed to the output array. If the conditional statement returns false, then the elements don’t get pushed to the output array.

Syntax

Filter Syntax

The syntax of map and filter is very similar, except the callback function should return true to keep the element or false otherwise.

Example

Filter Example

Output

Filter Example

Reduce

A reduce method is generally used to reduce an array of values just down to one value. For getting the output value it runs a reducer function on each element of an array.

Syntax

Reduce Example

The callback argument is a function that will be called once for every item in an array. The function generally takes four arguments but often only the first two are used.

  • accumulator:  It is used to return the value of the previous iteration.
  • currentValue: It is generally used for the current item in an array
  • index: It is used for the index of the current item
  • array: The original array on which reduce was called.
Example

Reduce Example

Output

Reduce Output

Video Explanation of the Topic

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay Connected

0FansLike
3,498FollowersFollow
19,400SubscribersSubscribe
- Advertisement -spot_img

Latest Articles