An animated guide to Array Filter

Last updated February 11, 2022 by Jacob Paris

When you filter an array, you get a new array with only the elements whose callback returned true

You can filter numbers that are below a certain value

JS

Filter numbers less than a value

Step 0/9

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers.filter(function (i) {
return i < 5
}
return [1, 2, 3, 4]

Or above a certain value

JS

Filter numbers greater than a value

Step 0/9

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers.filter(function (i) {
return i >= 6
}
return [6, 7, 8, 9]

Odds vs even

JS

Filter odd and even numbers

Step 0/9

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers.filter(function (i) {
return i % 2
}
return [1, 3, 5, 7, 9]

Boolean

JS

Remove falsy values with filter

Step 0/6

let cases = [1, NaN, 0, true, false, 25]
// cases.filter(Boolean)
cases.filter(function (i) {
return Boolean(i)
}
return [1, true, 25]