Map, Filter & Reduce functions in JavaScript

Map, filter and reduce functions were introduced in ES6. All of these functions transform an initial list (array) into something else, while keeping the original list intact. We can always use a for loop to get the desired result, but it can be much easier to use these methods and the code will stay cleaner and easier to read.

Map Function

The map() function creates a new array by calling a specific function on each element in an initial array. In the following example, each number in an array is doubled:

With for loop: With map() function:
let numbers = [1, 2, 3, 4];

let doubled = [];

for (let i = 0; i < numbers.length; i++) {

     doubled.push(numbers[i] * 2):

}

let numbers = [1, 2, 3, 4];

let doubled = numbers.map(num => num * 2); 

 

Filter Function

The filter() function creates a new array with elements from the initial array that pass a certain test. For example, the filter() function can be used to create a new array of only positive values:

With for loop: With filter() function:
let numbers = [1, -2, 3, -4];

let positive = [];

for (let i = 0; i < numbers.length; i++) {

     if (numbers[i] > 0) {

         positive.push(numbers[i]);

     }

}

let numbers = [1, -2, 3, -4];

let positive = numbers.filter(num => num > 0); 

 

Reduce Function

The reduce() function applies a specific function to all elements in an array and reduces it to a single value. Here is an example of summing up each number value in an array:

With for loop: With reduce() function:
let numbers = [1, 2, 3, 4];

let total = 0;

for (let i = 0; i < numbers.length; i++) {

     total += numbers[i];

}

let numbers = [1, 2, 3, 4];

let total = numbers.reduce((total, num) => total + num); 

 


“Map, Filter & Reduce functions in JavaScript” Tech Bite was brought to you by Nedim Hairlahović, Junior Software Engineer at Atlantbh. 

Tech Bites are tips, tricks, snippets or explanations about various programming technologies and paradigms, which can help engineers with their everyday job.

Leave a Reply