javascript · level 2 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
keeps the items that pass a test.
.filter() takes a function that answers true or false for each item. Items that get true go into a new array, and the rest are left out. scores.filter((score) => score >= 50) keeps the passing scores.
It shines with arrays of objects: keep the products under £5, the pets that are cats, the jobs not done yet.
Want only the first match? hands back that one item itself, not an array, or undefined if nothing passes the test.
const pets = [
{ name: "Rex", type: "dog" },
{ name: "Tibbles", type: "cat" },
{ name: "Mittens", type: "cat" },
];
const cats = pets.filter((pet) => pet.type === "cat");
console.log(cats.length, cats[0].name);
console.log(pets.find((pet) => pet.type === "dog")); A comma after the last item in a list is allowed, and it makes adding another item tidier.
guess first
Filter and find the teenagers. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const ages = [4, 12, 17, 9, 15];
const teens = ages.filter((age) => age >= 13);
const firstTeen = ages.find((age) => age >= 13);
console.log(teens, firstTeen);
your turn
Your turn. What can you afford?
Type how many pounds you have to spend. Press run to see how many snacks cost that much or less.
fix it
No books are left to read? Fix it!
- No book passes the test. What does the test inside
filterdo? - One
=putsfalseinto every book instead of asking a question. Asking needs three. - Change book.read = false to book.read === false on line 6, then press run.
nailed it
you can keep only what you need. :D
filterkeeps items whose test givestrue.- It always hands back a new array, maybe an empty one.
findhands back the first match itself.
new words in your collection
- filter
- find
This lesson isn’t saved. A free account remembers every lesson you finish.