map(), filter() and reduce() in JavaScript

For more such articles, visit www.knowledgescoops.com

Kunal Tandon
Developer’s Arena
2 min readApr 27, 2019

--

Prototype in JavaScript array have the map(), filter() and the reduce() method. We have been generally using these methods with an array. This article explains the usage of these methods that help to iterate, modifying the array with much ease.

The map() method

The map() method creates a new array from an existing array by modifying each item by the function that is passed to the map() method.

doubleValues now contains:

The map() returns a new array which contains the newly mapped elements which are stored in the doubleValues array.

The filter() method

The filter() method filters the elements and makes a subset of an array. The filter() methods accept a function returning a boolean as an argument. If the boolean method returns true, the value will be selected else the value will be rejected.

The above method filters the values and extracts out the larger values (greater than 3000) in a variable named largeValues.

largeValues now contains:

Similar to map() method, filter() also returns a new array of filtered elements that we have assigned in the array named largeValues.

The reduce() method

The reduce() method is different from the map() and filter(). Instead of creating a new array, it reduces the array to some concrete value (say sum of all array elements). It uses an accumulator to do so.

The reduce() method needs a callback as its first parameter which is defined as:

To actually use the reduce method, we write:

We get the output as:

The number 15 is the value returned by the reduce() method.

reduce() method can also take a second optional parameter like:

We get the output as:

The number 25 is the value returned by the reduce() method. The second parameter 10 is called the initialValue, that gets added to the array sum 15 with the iterations as defined in the above stack trace.

For more such articles, visit www.knowledgescoops.com

--

--