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.

When we deal with long text, we often want to truncate it so that it fits our UI design. Typically, we need whatever is too long to be displayed nicely to be replaced by an ellipsis, which is a set of dots (…) indicating that there is the text being…
Presenting data is not an easy task, however effortless it may seem to us when listening to some people do it. Especially when presenting your work. Good presentation needs effort, and more often than not, it requires practice. But even without much practice, we can present our data in a…
Introduction to Structuring APIs and unit tests in Express This tech bite will show you how to structure your JavaScript back-end code in such a way it is easier to search through, modular, scalable, and allows for writing unit tests. Writing APIs using Express.js initially seems quick and easy: it’s…