JavaScript Array.prototype.filter() Method
The filter() method creates a new array with only the elements that pass a test you provide. The original array is not changed.
Description
The filter() method creates a new array with every element for which the callback returns a truthy value. The original array is left unchanged, and the elements kept are the same values (objects are not copied).
It's the standard way to remove unwanted items, such as completed tasks or empty strings. To find just the first matching element, use find(), which stops searching as soon as it finds one. filter(Boolean) is a quick way to remove all falsy values.
The callback receives the index as its second argument, which allows filters based on position, and the array as its third, which lets you remove duplicates with arr.filter((v, i, a) => a.indexOf(v) === i), although [...new Set(arr)] is simpler and faster. Empty slots are skipped, so filtering also compacts sparse arrays.
Syntax
array.filter(callbackFn)
array.filter(callbackFn, thisArg)Parameters
- callbackFnA function that tests each element. Return a truthy value to keep the element. It receives
element,indexandarray. - thisArgOptional. A value to use as
thisinsidecallbackFn.
Return Value
A new array containing only the elements that passed the test (a shallow copy). It is empty if none passed.
Example
Browser Support
The following information will show you the current browser support for the Array.prototype.filter() method. Hover over a browser icon to see the version that first introduced support for this method.
Desktop





Tablets & Mobile





