Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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, 20

Removing empty values

Passing Boolean removes empty strings, zeros, null and undefined:

console.log(['a', '', 'b', null, 'c'].filter(Boolean).join(', '));

Output:

a, b, c

Objects

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:

Tea

Several 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:

Tea

Common 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
Oleg

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.