filter: Keep Only Some

Grade 10, page 4 of 12. A one-minute read.

filter creates a new array containing only the items that pass a test. Your callback should return true (keep it) or false (throw it away):

JavaScript
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const evens = numbers.filter((n) => n % 2 === 0);
const bigOnes = numbers.filter((n) => n > 6);

console.log(evens);
console.log(bigOnes);

It prints

[ 2, 4, 6, 8, 10 ]
[ 7, 8, 9, 10 ]

The new array can be shorter than the original, or even empty if nothing passes. The original is never changed.

JavaScript
const students = [
  { name: "Mia", score: 88 },
  { name: "Omar", score: 45 },
  { name: "Zoe", score: 95 },
  { name: "Sam", score: 61 },
];

const passed = students.filter((s) => s.score >= 50);
const stars = students.filter((s) => s.score >= 90);

console.log(passed.length);
console.log(stars);

It prints

3
[ { name: 'Zoe', score: 95 } ]

filter is perfect for search features. Here's a mini search box for a list of foods:

JavaScript
const menu = ["fried rice", "coconut rice", "omelet", "rice balls", "waffle"];
const search = "rice";

const results = menu.filter((dish) => dish.includes(search));
console.log(results);

It prints

[ 'fried rice', 'coconut rice', 'rice balls' ]

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning