Table of Contents
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
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:
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
The syntax of map and filter is very similar, except the callback function should return true to keep the element or false otherwise.
Example
Output
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
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.