Array.prototype.filter()

Examples

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const evenNumbers = numbers.filter((num) => num % 2 === 0)

console.log(evenNumbers) // [2, 4, 6, 8, 10]
const words = ['apple', 'banana', 'cherry', 'date', 'elderberry']
const fiveLetterWords = words.filter((word) => word.length === 5)

console.log(fiveLetterWords) // ['apple', 'cherry', 'date']

Syntax

array.filter(callback(element[, index[, array]])[, thisArg])

Description

The JavaScript Array.prototype.filter() method is a higher-order function that allows you to create a new array with all elements that pass a test implemented by a provided function. It is a useful method for filtering out unwanted elements from an array and creating a new array with only the desired elements.

The filter() method takes a callback function as its first argument. This callback function is called for each element in the array, and it should return a boolean value indicating whether the element should be included in the new filtered array. If the callback function returns true for a given element, that element will be included in the new array. If it returns false, the element will be excluded.

The callback function can take up to three arguments:

  • element: the current element being processed in the array
  • index (optional): the index of the current element in the array
  • array (optional): the array the filter() method was called on

The filter() method also takes an optional second argument, which is used as the this value inside the callback function.

Specifications

  • The filter() method is part of the Array.prototype, which means it is available to be used on any array object.
  • The filter() method does not modify the original array, but rather creates a new array with the elements that pass the test implemented by the callback function.
  • The filter() method is a useful way to select a subset of elements from an array based on a certain criterion.

Browser Compatibility

The filter() method is supported in all modern browsers, including Internet Explorer 9 and above.

Similar Methods

There are several other methods in JavaScript that allow you to select elements from an array based on certain criteria. Some examples include:

  • Array.prototype.map(): creates a new array with the results of calling a provided function on every element in the original array
  • Array.prototype.find(): returns the value of the first element in the array that satisfies the provided testing function
  • Array.prototype.some(): tests whether at least one element in the array passes the test implemented by the provided function