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.

oban
Software DevelopmentTech Bites
February 23, 2024

Background Jobs in Elixir – Oban

When and why do we need background jobs? Nowadays, background job processing is indispensable in the world of web development. The need for background jobs stems from the fact that synchronous execution of time-consuming and resource-intensive tasks would heavily impact an application's  performance and user experience.  Even though Elixir is…
selenium
QA/Test AutomationTech Bites
December 22, 2023

Selenium Grid 4 with Docker

Introduction When talking about automation testing, one of the first things that comes to mind is Selenium. Selenium is a free, open-source automated testing framework used to validate web applications across different browsers and platforms. It is not just a single tool but a suite of software. Every component of…

Want to discuss this in relation to your project? Get in touch:

Leave a Reply