Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Array

JavaScript Array filter() method

Reference for JavaScript Array filter(): create a new array of the elements that pass a test, with the callback arguments, edge cases and examples.

The filter() method creates a new array containing only the elements for which your callback returns a truthy value. The original array is not changed, and the elements keep their original order.

It is the standard way to answer "which items match?". If no element passes, you get an empty array, never undefined.

JavaScript
[1, 2, 3, 4].filter((n) => n % 2 === 0); // [2, 4]

Try it

JS Keeping what matches

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Index, array and duplicates

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
filter(callbackFn)
filter(callbackFn, thisArg)
Name Description
callbackFn Called as callbackFn(element, index, array). Return a truthy value to keep the element.
thisArg Optional. Value used as this inside callbackFn (ignored by arrow functions).

Return value: a new array holding the elements that passed, possibly empty.

Exceptions: a TypeError if callbackFn is not a function.

Usage notes

  • It never mutates the source, but the result is only a shallow copy: objects in the new array are the same objects as in the old one, as the last example shows.
  • Truthy, not true. Any truthy return keeps the element, so filter(Boolean) is a common idiom for dropping 0, "", null, undefined, false and NaN. Be careful when 0 is valid data.
  • Always returns an array. Use find() when you want a single element, or some() when you only need a yes or no.
  • Holes are skipped, so filter() also removes empty slots from a sparse array.
  • Remove by condition: to delete matching items, keep the others: list = list.filter((x) => x.id !== idToRemove).
  • Callback arguments: the index and array parameters make tricks like removing duplicates possible, although a Set is faster for large arrays.
  • Not a mapping tool. The callback decides keep or drop; it cannot change elements. Chain map() after filter() to transform the survivors.
  • Types: TypeScript users can pass a type guard to narrow the result type, but that is a typing feature, not a runtime one.

Browser support

filter() is supported in every current browser.