.filter()
Array method that returns a new array containing only the elements that pass a test. The original array is never modified.
When to use it
- Narrowing data — keep only items that match a condition
- Removing items — non-mutating alternative to
splice - Search results — filter a list by user input
- Chaining — combine with
.map()to filter then transform
Anatomy
const result = array.filter((element, index, array) => {
// return true to keep the element, false to discard it
return condition
})At a glance
| Parameter | What it is |
|---|---|
element | Current item being tested |
index | Position in the array (0-based) |
array | The original array (rarely needed) |
| Return value | New array with elements where callback returned truthy |
1. Simple — keep matching items
const nums = [1, 2, 3, 4, 5]
const evens = nums.filter(n => n % 2 === 0)
evens // [2, 4]
nums // [1, 2, 3, 4, 5] — untouched2. Intermediate — filter objects by property
const tasks = [
{ title: 'Write tests', done: true },
{ title: 'Fix bug', done: false },
{ title: 'Deploy', done: false },
]
const remaining = tasks.filter(t => !t.done)
// [{ title: 'Fix bug', done: false }, { title: 'Deploy', done: false }]3. Advanced — search with multiple conditions
function searchProducts(products, query, maxPrice) {
return products.filter(p => {
const matchesQuery = p.name.toLowerCase().includes(query.toLowerCase())
const withinBudget = p.price <= maxPrice
return matchesQuery && withinBudget
})
}
const products = [
{ name: 'Wireless Mouse', price: 25 },
{ name: 'Wireless Keyboard', price: 60 },
{ name: 'USB Mouse', price: 10 },
]
searchProducts(products, 'mouse', 30)
// [{ name: 'Wireless Mouse', price: 25 }, { name: 'USB Mouse', price: 10 }]Gotchas
Empty results return an empty array, not null
const nums = [1, 2, 3]
const result = nums.filter(n => n > 10)
result // [] — empty array, not null or undefined
result.length // 0Falsy values and truthy shorthand
const mixed = [0, 1, '', 'hello', null, undefined, false, true]
// Boolean as a callback removes all falsy values
mixed.filter(Boolean) // [1, 'hello', true]
// be careful — 0 and '' are valid data that gets removed
const prices = [0, 10, 25]
prices.filter(Boolean) // [10, 25] — lost the free item!
prices.filter(p => p !== null && p !== undefined) // [0, 10, 25] — correctRelated
Last updated on