Map vs Filter vs Reduce Javascript

How to Use Map, Filter, and Reduce in JavaScript

Map, reduce, and filter are all array methods in JavaScript. Each one will iterate over an array and play out a change or calculation. 

Each will return a new array based on the result of the function. In this article, you will realize & learn why and how to utilize every one.

Map

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

Syntax:

In the callback, only the array element is required. Usually some action is performed on the value and then a new value is returned.

Example

In the following example, each number in an array is doubled.


Filter


The filter() method takes each element in an array and it applies a conditional statement against it.
If this conditional returns true, the element gets pushed to the output array. If the condition returns false, the element does not get pushed to the output array.

Syntax:

the syntax for filter is similar to map, except the callback function should return true to keep the element, or false otherwise. In the callback, only the element is required.


Examples
In the following example, odd numbers are "filtered" out, leaving only even numbers.


Reduce
The reduce() method reduces an array of values down to just one value. To get the output value, it runs a reducer function on each element of the array.


Syntax:



The callback argument is a function that will be called once for every item in the array. This function takes four arguments, but often only the first two are used.
accumulator - the returned value of the previous iteration
currentValue - the current item in the array
index - the index of the current item
array - the original array on which reduce was called
The initialValue argument is optional. If provided, it will be used as the initial accumulator value in the first call to the callback function.


Examples
The following example adds every number together in an array of numbers.















Post a Comment

Previous Post Next Post