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.
[1, 2, 3, 4].filter((n) => n % 2 === 0); // [2, 4]
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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, sofilter(Boolean)is a common idiom for dropping0,"",null,undefined,falseandNaN. Be careful when0is valid data. - Always returns an array. Use
find()when you want a single element, orsome()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
indexandarrayparameters make tricks like removing duplicates possible, although aSetis faster for large arrays. - Not a mapping tool. The callback decides keep or drop; it cannot change elements. Chain
map()afterfilter()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.