Filter & Reduce functions in JavaScript

Loops are an important construct of every programming language. They are also a tool generally used to perform operations on an array in any programming language. But, instead of using standard loop constructions (for, while,…), JavaScript provides more elegant ways to iterate through an array and perform desired operations. Observe the example below, which calculates the sum of all elements in the array:

Map, filter and reduce 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:

const array = [1, 2, 3, 4, 5];	
  let result = 0;
  for (let i = 0; i < array.length; i++) {
       result += array[i];
  }  

The same operation (which is pretty simple) can be done in only one line of code, as it is shown in the following code snippet:

const array = [1, 2, 3, 4, 5];	
  const result = array.reduce(
(accumulator, item) => accumulator += item, 0);

The reduce function accepts two arguments - callbackand initialValue. callbackis a reducer function – a function which should be applied on every element of the array. It is specified with two required parameters - accumulatorwhich is a resultant collection from the previous iteration and itemwhich is the current item being processed from the input array. initialValueis the value the reduce function starts with.

Now, let’s find all elements in the array which are greater than 3 using the reduce function:

const array = [1, 2, 3, 4, 5];	
  const result = array.reduce((accumulator, item) => {
     if (item > 3) {
        accumulator.push(item);
     }
     return accumulator;
  }, []);

What happened with the only-one-line rule for the reducefunction and simple operation? Although thereducefunction can be used to get all elements greater than 3, it is not the best possible choice for this case, from a readability point of view, because in this use case there is nothing to reduce – it’s all about filtering, so let’s filter them:

const array = [1, 2, 3, 4, 5];	
  const result = array.filter(item => item > 3);

Thefilterfunction is used to filter out the items from the input array. This function accepts only one argument –callback, which defines the filtering criteria. If callbackreturnsfalse, the item is rejected, and, ifcallbackreturns true, the item is being added to a new array.


“Filter & Reduce functions in JavaScript” Tech Bite was brought to you by Maid Bajramović, 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.

Dynamic programming
Software DevelopmentTech Bites
December 9, 2022

Dynamic Programming

Dynamic programming is both a mathematical optimization method and a computer programming method. By definition, it is a technique in computer programming that helps to efficiently solve a class of problems with overlapping subproblems and optimal substructure properties. It refers to simplifying a complicated problem by breaking it into simpler…

Leave a Reply