Skip to content

JavaScript Array filter Method Explained

JavaScript/

The filter method can be used to obtain a new array that contains only the elements that we want from an already existing array. When invoked on an array, it returns a new array that contains only the elements that meet the given requirements, leaving the original array unaffected.

How It Works

The filter method loops through every element of an array that it is invoked on. It passes each element to a callback function that contains some testing logic that checks if the element is acceptable. After checking every element, the filter method returns a new array containing only the suitable elements from the original array that passed the provided test.

The callback function is up to you to implement. It is a required parameter of the filter method. When the filter method checks each element of the array, it passes the current element to the callback function through the callback function’s first parameter, which means that it is a required parameter of the callback function.

The callback function must contain logic that returns an value that can be evaluated to true or false. Here are examples of truthy and falsy values. The elements, on which the callback function returns true, will be placed in the resulting array that will be returned by filter.

Let’s consider the following code.

const fruits = ['apple', 'orange', 'banana', 'watermelon'];

function isWatermelon(fruit) {
  if (fruit === 'watermelon') {
    return true;
  }

  return false;
}

// ['watermelon']
const watermelons = fruits.filter(isWatermelon);

In this example, the filter method will go over each fruit in the fruits array and call the isWatermelon function, passing the current element through the fruit parameter. It will return false on every element that is not watermelon. Since the last element in the fruits array is watermelon, on which the isWatermelon function returns true, the watermelons variable will contain an array that contains one element - watermelon.

It’s up to you how to name the callback function and its parameter. Which means you could also do something like this.

const fruits = ['apple', 'orange', 'banana', 'watermelon'];

function isWordSixCharactersLong(word) {
  return word.length === 6;
}

// ['orange', 'banana']
const wordsLengthOfSix = fruits.filter(isWordSixCharactersLong);

Also, you don’t have to use named functions. You can pass an anonymous function to the filter method.

const fruits = ['apple', 'orange', 'banana', 'watermelon'];

// ['apple']
const startsWithA = fruits.filter(function(name) {
  return name[0] === 'a';
});

You can also use arrow functions to shorten the expression.

const fruits = ['apple', 'orange', 'banana', 'watermelon'];

// ['orange', 'banana']
fruits.filter(fruit => {
  return fruit.includes('an');
});

// ['orange', 'watermelon']
fruits.filter(fruit => fruit.includes('o'));

References