filter
Keep the items that pass a test. Same items, fewer of them.
filter runs your test once per item and hands back a new array of the ones that passed: same items, same order, input untouched.
The function is a question about one item: is it active, did it pass, is it in this topic. Combine with .length to count and with map to reshape what survived.
Shape
const kept = items.filter((item) => booleanTest); Patterns
-
results.filter((r) => r.correct)Keep by a boolean field.
-
results.filter((r) => r.correct).lengthCount matches.
-
results.filter((r) => !r.answered).map((r) => r.questionId)Filter then map: narrow first, then reshape.
-
values.filter((v) => v !== null && v !== undefined)Be precise about what you drop.
Pitfalls
filterwants a boolean. Returning the item itself, or a transformed value, keeps everything truthy and confuses readers.filter(Boolean)drops0,""andfalsealong withnullandundefined. Fine for strings, wrong for scores.- If you only need the first match,
findstops early.filterscans everything.
Exercises
Write the function, run it against the hidden cases. Cmd or Ctrl + Enter runs, Tab indents, Esc then Tab leaves the editor. 0 / 6 solved.
1. Passed results
Return only the results where passed is true.
passedResults(
[
{ id: 1, passed: true },
{ id: 2, passed: false },
{ id: 3, passed: true }
]
) → [{ id: 1, passed: true }, { id: 3, passed: true }] 2. Count correct
Return how many results have correct: true.
countCorrect([{ correct: true }, { correct: false }, { correct: true }]) → 2 3. Unanswered ids
Return the questionId of every result where answered is false, in input order.
unansweredIds(
[
{ questionId: "q3", answered: false },
{ questionId: "q1", answered: true },
{ questionId: "q2", answered: false }
]
) → ["q3", "q2"] 4. Active in topic
Return the students who are active and whose topics list includes the given topic.
activeInTopic(
[
{ name: "Ana", active: true, topics: ["vitals", "safety"] },
{ name: "Bo", active: false, topics: ["vitals"] },
{ name: "Cy", active: true, topics: ["safety"] }
],
"vitals"
) → [{ name: "Ana", active: true, topics: ["vitals", "safety"] }] 5. Drop only empties
Remove null, undefined and empty strings from the list. Everything else stays, including 0 and false, which a truthiness check would wrongly drop.
dropEmpties([0, "", null, "a", false, undefined, 5])
→ [0, "a", false, 5] 6. Stale documents
Return the documents whose updatedAt (an ISO string) is strictly before the given cutoff (also an ISO string). A document updated exactly at the cutoff is not stale. Keep input order.
staleDocuments(
[
{ id: 1, updatedAt: "2026-09-01T00:00:00Z" },
{ id: 2, updatedAt: "2026-09-20T00:00:00Z" },
{ id: 3, updatedAt: "2026-09-09T23:59:59Z" }
],
"2026-09-10T00:00:00Z"
) → [
{ id: 1, updatedAt: "2026-09-01T00:00:00Z" },
{ id: 3, updatedAt: "2026-09-09T23:59:59Z" }
] Fold a list into one value: a number, an object, or a new list.