filter creates a new array with only the elements where your callback returns true. Everything else is excluded.
You can read filter: Keeping What Matters and try the first 1 exercise on the free plan. Upgrade to unlock the remaining 2 exercises and continue the full lesson flow.
Pro: every unit of every course · unlimited hearts · no weekly limit on assessment attempts
Complete lesson & earn 250 PX
EXERCISE
1The filter method creates a new array containing only the elements where your callback function returns true. Everything else is excluded.
filter builds a new array containing only the elements for which your function returned a truthy value. It does not modify the original array and it does not modify the elements, so the result is always the same length or shorter, holding the same values that were already there. The function you pass is called once per element and its return value is read as a yes or a no.
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter((n) => n % 2 === 0);
console.log(evens); // [2, 4, 6]
console.log(numbers); // [1, 2, 3, 4, 5, 6]
The distinction from map is worth stating plainly: map decides what each element becomes, filter decides whether each element stays. The callback of one returns a value; the callback of the other returns a verdict.
On objects, the test is usually a property:
const users = [
{ name: "Ada", active: true },
{ name: "Alan", active: false },
{ name: "Grace", active: true },
];
const active = users.filter((u) => u.active);
console.log(active.length); // 2
The elements in active are the same objects that are in users, not copies. Changing one changes both, because filter selects references rather than duplicating what it selects.
Nothing matching is not an error:
const none = numbers.filter((n) => n > 100);
console.log(none); // []
console.log(none.length); // 0
An empty array, which is safe to iterate and safe to chain. This is the quiet advantage over an index-based search: there is no -1 to remember and no undefined to guard against.
The most common mistake is forgetting to return:
const wrong = numbers.filter((n) => {
n % 2 === 0;
});
console.log(wrong); // []
The block returns undefined, which is falsy, so every element is rejected and the result is empty. An empty array from a filter you expected to match something is almost always this, rather than a wrong condition.
filter also passes the index and the whole array to your callback, which makes positional tests possible:
const items = ["a", "b", "c", "d"];
const everyOther = items.filter((value, index) => index % 2 === 0);
console.log(everyOther); // ["a", "c"]
Using the third parameter is rarer, but it is what lets a filter compare an element against its neighbours without closing over the array separately.
filter returns the same or fewer elements. Chain with map for powerful data pipelines. Use .filter(Boolean) to remove all falsy values (false, 0, "", null, undefined, NaN).