filter
Keep some items.
Show only the products that are in stock. Only the emails that are unread. Only the scores above fifty. Filter keeps the items that pass a test, and drops the rest.

- Only in stock
- Only unread
- filter keeps what passes
Keep what passes
Filter calls your callback for each item. If it returns true, the item is kept in the new array. If it returns false, it's dropped. Run it. The new array can be shorter, or even empty.
const scores = [45, 82, 67, 30, 91];
const passed = scores.filter(s => s >= 50);
console.log(passed);
const words = ["sun", "moon", "star", "sky"];
console.log(words.filter(w => w.length > 3));
console.log(words.filter(w => w.startsWith("z")));[ 82, 67, 91 ] [ 'moon', 'star' ] []
Filter and find
Filter returns every match, as an array. Find returns only the first match, as a single item. So if you want all the cheap products, use filter. If you want just one product by its ID, use find. Like map, filter never changes the original.
| key | value |
|---|---|
| filter(fn) | all matches |
| find(fn) | first match |
| Can be empty | [] |
| Original | unchanged |
Filtering objects
Filter really shines with arrays of objects. Here we keep the products that are in stock, and cheaper than ten dollars. We can combine conditions with and. Then we map to just the names. Filter never changes the original array. Run it.
const products = [
{ name: "Pen", price: 2, inStock: true },
{ name: "Lamp", price: 25, inStock: true },
{ name: "Mug", price: 8, inStock: false },
{ name: "Notebook", price: 5, inStock: true },
];
const cheap = products.filter(p => p.inStock && p.price < 10);
console.log(cheap.map(p => p.name));
console.log(products.length);[ 'Pen', 'Notebook' ] 4
Summary
Filter keeps the items that pass a test, in a new array. Next, reduce, which combines everything into one value.
Key takeaways- arr.filter(x => test)
- Shorter array
- filter vs find