×

javascript · level 2 · unit 6 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.