Learn JavaScript
❯ arrays.filter

filter: Selecting Elements in JavaScript

$concept

filter keeps elements passing a predicate: [1,2,3,4].filter(x => x % 2 === 0) is [2,4]. Like map it returns a fresh array without touching the input; unlike map, output length varies (possibly zero). The predicate sees (value, index, array) for positional rules.

filter-then-map chains read as pipelines (actives.filter(...).map(...)), and combining with Boolean removes all falsy values in one idiom (arr.filter(Boolean)). For first-match-only needs, find() stops early instead of scanning everything.

$how it works
1

Keep what passes

Truth-returning elements survive in order; the rest vanish β€” output is a subset, possibly empty.

2

Pure like map

Input untouched, fresh array returned β€” safe to chain and re-run.

3

filter(Boolean) cleans

Drops all eight falsy values at once β€” the standard null/empty scrubber.

4

find for first-only

Need one match, not all? find() stops at the first hit instead of scanning the tail.

$example
let nums = [1, 2, 3, 4, 5];
let evens = nums.filter(n => n % 2 === 0);
console.log(evens, evens.length);
Output
[ 2, 4 ] 2
1The predicate keeps 2 and 4, dropping odds β€” order preserved.
2A new two-element array returns; nums still holds all five.
3Both print β€” subset plus its length.
$use cases
Search results and faceted lists from master arrays
Removing invalid/empty entries with filter(Boolean)
Chained pipelines (filter then map) reading as data flow
Permission and visibility filtering in UIs

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself β€” building beats watching.