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):
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.
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:
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' ]