How to filter an array
Short answer
filter() keeps the elements for which the function returns true:
console.log([5, 12, 8, 20].filter((n) => n > 10).join(', '));Output:
12, 20Removing empty values
Passing Boolean removes empty strings, zeros, null and undefined:
console.log(['a', '', 'b', null, 'c'].filter(Boolean).join(', '));Output:
a, b, cObjects
The condition may test any property:
const tasks = [
{ title: 'Tea', done: true },
{ title: 'Coffee', done: false },
];
console.log(tasks.filter((task) => task.done).map((task) => task.title).join(', '));Output:
TeaSeveral conditions
Combine conditions with && and || inside the function:
const products = [
{ name: 'Tea', price: 3, inStock: true },
{ name: 'Cake', price: 12, inStock: true },
{ name: 'Coffee', price: 5, inStock: false },
];
console.log(products.filter((p) => p.inStock && p.price < 10).map((p) => p.name).join(', '));Output:
TeaCommon mistake
filter() always returns an array, even for one match. To get a single element, use find():
const users = [{ id: 1, name: 'Anna' }, { id: 2, name: 'Oleg' }];
console.log(users.filter((user) => user.id === 2).name);
console.log(users.find((user) => user.id === 2).name);Output:
undefined
OlegFunctions used in this recipe
- Array.prototype.filter — Creates a new array from the elements that pass a test.
- Array.prototype.find — Returns the first element that passes a test.
- Array.prototype.map — Creates a new array by transforming every element.