Array.prototype.filter()
BaselineWidely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Thefilter()
method ofArray
instances creates ashallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
Try it
const words = ["spray", "elite", "exuberant", "destruction", "present"];const result = words.filter((word) => word.length > 6);console.log(result);// Expected output: Array ["exuberant", "destruction", "present"]
Syntax
filter(callbackFn)filter(callbackFn, thisArg)
Parameters
callbackFn
A function to execute for each element in the array. It should return atruthy value to keep the element in the resulting array, and afalsy value otherwise. The function is called with the following arguments:
thisArg
OptionalA value to use as
this
when executingcallbackFn
. Seeiterative methods.
Return value
Ashallow copy of the given array containing just the elements that pass the test. If no elements pass the test, an empty array is returned.
Description
Thefilter()
method is aniterative method. It calls a providedcallbackFn
function once for each element in an array, and constructs a new array of all the values for whichcallbackFn
returns atruthy value. Array elements which do not pass thecallbackFn
test are not included in the new array. Read theiterative methods section for more information about how these methods work in general.
callbackFn
is invoked only for array indexes which have assigned values. It is not invoked for empty slots insparse arrays.
Thefilter()
method isgeneric. It only expects thethis
value to have alength
property and integer-keyed properties.
Examples
Filtering out all small values
The following example usesfilter()
to create a filtered array that has all elements with values less than 10 removed.
function isBigEnough(value) { return value >= 10;}const filtered = [12, 5, 8, 130, 44].filter(isBigEnough);// filtered is [12, 130, 44]
Find all prime numbers in an array
The following example returns all prime numbers in the array:
const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];function isPrime(n) { if (n < 2) { return false; } if (n % 2 === 0) { return n === 2; } for (let factor = 3; factor * factor <= n; factor += 2) { if (n % factor === 0) { return false; } } return true;}console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13]
Note:TheisPrime()
implementation is for demonstration only. For a real-world application, you would want to use a heavily memoized algorithm such as theSieve of Eratosthenes to avoid repeated calculations.
Filtering invalid entries from JSON
The following example usesfilter()
to create a filtered JSON of all elements with non-zero, numericid
.
const arr = [ { id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }, {}, { id: null }, { id: NaN }, { id: "undefined" },];let invalidEntries = 0;function filterByID(item) { if (Number.isFinite(item.id) && item.id !== 0) { return true; } invalidEntries++; return false;}const arrByID = arr.filter(filterByID);console.log("Filtered Array\n", arrByID);// Filtered Array// [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]console.log("Number of Invalid Entries =", invalidEntries);// Number of Invalid Entries = 5
Searching in array
Following example usesfilter()
to filter array content based on search criteria.
const fruits = ["apple", "banana", "grapes", "mango", "orange"];/** * Filter array items based on search criteria (query) */function filterItems(arr, query) { return arr.filter((el) => el.toLowerCase().includes(query.toLowerCase()));}console.log(filterItems(fruits, "ap")); // ['apple', 'grapes']console.log(filterItems(fruits, "an")); // ['banana', 'mango', 'orange']
Using the third argument of callbackFn
Thearray
argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first usesmap()
to extract the numerical ID from each name and then usesfilter()
to select the ones that are greater than its neighbors.
const names = ["JC63", "Bob132", "Ursula89", "Ben96"];const greatIDs = names .map((name) => parseInt(name.match(/\d+/)[0], 10)) .filter((id, idx, arr) => { // Without the arr argument, there's no way to easily access the // intermediate array without saving it to a variable. if (idx > 0 && id <= arr[idx - 1]) return false; if (idx < arr.length - 1 && id <= arr[idx + 1]) return false; return true; });console.log(greatIDs); // [132, 96]
Thearray
argument isnot the array that is being built — there is no way to access the array being built from the callback function.
Using filter() on sparse arrays
filter()
will skip empty slots.
console.log([1, , undefined].filter((x) => x === undefined)); // [undefined]console.log([1, , undefined].filter((x) => x !== 2)); // [1, undefined]
Calling filter() on non-array objects
Thefilter()
method reads thelength
property ofthis
and then accesses each property whose key is a nonnegative integer less thanlength
.
const arrayLike = { length: 3, 0: "a", 1: "b", 2: "c", 3: "a", // ignored by filter() since length is 3};console.log(Array.prototype.filter.call(arrayLike, (x) => x <= "b"));// [ 'a', 'b' ]
Specifications
Specification |
---|
ECMAScript® 2026 Language Specification # sec-array.prototype.filter |