AI Hints
Home›JavaScript Tutorial›map, filter, reduce
JavaScript · Lesson 50 of 138

filter

Keep some items.

⏱ 2 min read▶ Video at 1:00:53🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

filter
From the video: filter
  • 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.

app.jsjavascript
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")));
Output
[ 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.

keyvalue
filter(fn)all matches
find(fn)first match
Can be empty[]
Originalunchanged

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.

app.jsjavascript
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);
Output
[ '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
Next up: reduce — combine into one