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
Example
#const scores = [45, 82, 67, 91, 30]
const passed = scores.filter((score) => score >= 60)
console.log(passed)
console.log(scores.length)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
#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
Thethisvalue inside the function. Doesn’t matter with arrow functions.
More examples
#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))const values = ['Emma', '', null, 'Jack', undefined, 0]
console.log(values.filter(Boolean))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()withmap(), but remember each method walks the array separately. For very large data sets, consider a singlereduce().
Related entries
#- find() vs filter()find() returns the first element that matches a condition, or undefined, while filter() returns a new array with every element that passed the test.
- Array.prototype.map()Creates a new array with the results of calling a function for every element.
- Array.prototype.find()Returns the first element that matches a condition, or undefined.
- Array.prototype.some()Checks whether at least one element matches a condition.
- Array.prototype.reduce()Reduces the whole array to a single value, such as a sum, an object, or a new array.
Spotted a mistake or missing an example? Write to us.