🚦

filter()

🎉
💨
Only the worthy shall pass! filter() is like a gatekeeper!

The filter() Method

The filter() method creates a new array with only the items that pass a test.

Items that return true get through; items that return false are left behind!

💡
💨

How filter() Works

1const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2
3// Keep only even numbers
4const evens = numbers.filter(n => n % 2 === 0);
5console.log(evens); // [2, 4, 6, 8, 10]
6
7// Keep only numbers greater than 5
8const big = numbers.filter(n => n > 5);
9console.log(big); // [6, 7, 8, 9, 10]
10
11// Original is unchanged
12console.log(numbers); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
🤔
💨

filter() vs find()

filter()

  • Returns ALL matches
  • Returns an array
  • Can be empty []

find()

  • Returns FIRST match
  • Returns single item
  • Or undefined
🎮

Try It Yourself!

Click a filter to let only certain numbers through the gate!

🚦
[
1
[0]
2
[1]
3
[2]
4
[3]
5
[4]
6
[5]
7
[6]
8
[7]
9
[8]
10
[9]
]
length: 10