JavaScriptArrays

Array.prototype.filter()

Creates a new array with the elements for which the function returned true.

Returns
A new array with the elements that passed the test (it can be empty).
Changes the original
No
On this page

Example

#
JavaScript
const scores = [45, 82, 67, 91, 30]
const passed = scores.filter((score) => score >= 60)

console.log(passed)
console.log(scores.length)
Console
[82, 67, 91]
5

Definition and usage

#

The filter() method checks every array element with a testing function. Elements for which the function returns a truthy value end up in the new array, and the rest are skipped. The original is left unchanged.

It’s the basic tool for picking out data: active users, tasks still to do, products in a given category, or search results.

The result is always an array. If no element matches, you get an empty array [], not undefined. When you only need the first matching element, find() is faster and clearer.

Syntax

#
Syntax
array.filter(callbackFn)
array.filter(callbackFn, thisArg)

Parameters

#
  • callbackFn

    function (element, index, array)

    The testing function. An element ends up in the result if it returns a truthy value.
  • thisArg

    optional

    The this value inside the function. Doesn’t matter with arrow functions.

More examples

#
Filtering objects
JavaScript
const tasks = [
  { title: 'HTML module', done: true },
  { title: 'CSS module', done: false },
  { title: 'JS module', done: false }
]

const todo = tasks.filter((task) => !task.done)
console.log(todo.map((task) => task.title))
Console
['CSS module', 'JS module']
Removing empty values
JavaScript
const values = ['Emma', '', null, 'Jack', undefined, 0]
console.log(values.filter(Boolean))
Console
['Emma', 'Jack']

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • filter(Boolean) is a quick way to drop empty strings, null, undefined, and zeros. Just watch out when 0 is a valid value.
  • Combine filter() with map(), but remember each method walks the array separately. For very large data sets, consider a single reduce().

Related entries

#

Spotted a mistake or missing an example? Write to us.