🎉
💨
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];23// Keep only even numbers4const evens = numbers.filter(n => n % 2 === 0);5console.log(evens); // [2, 4, 6, 8, 10]67// Keep only numbers greater than 58const big = numbers.filter(n => n > 5);9console.log(big); // [6, 7, 8, 9, 10]1011// Original is unchanged12console.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