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.

Protractor parallel execution
QA/Test AutomationTech Bites
May 12, 2023

Protractor parallel execution

Why Parallel Testing? When designing automation test suites, the ability to run tests in parallel is a key feature because of the following benefits: Execution time - Increasing tests efficiency and, finally, faster releases Device compatibility - There are many devices with various versions and specifications that need to be…
Introduction to GraphQL
QA/Test AutomationTech Bites
May 11, 2023

Introduction to GraphQL

In today's Tech Bite topic, we will get familiar with GraphQL and explain its growth in popularity in recent years as the new standard for working with APIs. What is GraphQL? GraphQL stands for Graph Query Language. It is an API specification standard and, as its name says - a…

Leave a Reply