JavaScriptEasy
What is the filter() method?
filter() returns a new array containing only the elements for which the callback returns a truthy value; it never changes the original array and the result can be any length, including empty.
Signature
array.filter((element, index, array) => keep, thisArg?)
Typical uses
- Search results: items whose name includes a query.
- Removing items immutably:
todos.filter(t => t.id !== idToDelete), the standard way to delete from React state. - Cleaning data:
values.filter(Boolean)removesnull,undefined,0,"",NaNandfalse. - Removing duplicates (small arrays):
list.filter((x, i) => list.indexOf(x) === i). For large arrays use aSet.
Things to know
filteralways walks the whole array. If you only need the first match, usefind(orsomefor a yes/no), which stop early.- The returned elements are the same objects, not copies. Mutating them changes the originals.
filter(Boolean)also drops0, which is a bug when zeros are valid values. Be explicit:filter(x => x != null).- In TypeScript, a type predicate (
(x): x is User => ...) letsfilternarrow the resulting type.
Chaining
filter pairs naturally with map and reduce. For very large arrays, a single reduce or loop avoids creating intermediate arrays.
Code example
js
1const users = [2 { name: "Ada", age: 36, active: true },3 { name: "Linus", age: 17, active: false },4 { name: "Grace", age: 45, active: true },5];67const activeAdults = users.filter((u) => u.active && u.age >= 18);8console.log(activeAdults.map((u) => u.name)); // ["Ada", "Grace"]910// Immutable delete (React-style)11const remaining = users.filter((u) => u.name !== "Linus");12console.log(remaining.length, users.length); // 2 31314// Search15const query = "a";16console.log(users.filter((u) => u.name.toLowerCase().includes(query)).length); // 21718// filter(Boolean) drops ALL falsy values, including 019const raw = [0, 1, null, 2, "", 3, undefined, NaN];20console.log(raw.filter(Boolean)); // [1, 2, 3]21console.log(raw.filter((x) => x != null && !Number.isNaN(x) && x !== "")); // [0, 1, 2, 3]2223// Need just one? find stops at the first match24console.log(users.find((u) => u.age > 40)?.name); // Grace
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.