Sub topic 5
filter: Keeping Only What Matches
This chapter assumes you know arrow functions, truthy and falsy values, and the callback arguments covered earlier (element, index, array). filter is the method you use when the question is "which of these elements do I keep?" rather than "how do I change each one?"
The Working Model
filter calls your callback once for each element. The callback is a predicate, meaning a function that answers yes or no. If it returns a truthy value, the element is copied into a new array. If it returns a falsy value, the element is left out. The original array is not changed.
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] (unchanged)Compared with map, the result follows different rules:
| Property | map | filter |
|---|---|---|
| Result length | Always equals the input length | Anywhere from 0 to the input length |
| Elements in result | Whatever the callback returns | The original elements themselves |
| Callback's job | Produce a new value | Answer keep or drop |
Truthy, Not Just true
filter checks truthiness, so the predicate does not have to return a boolean. Passing Boolean as the predicate is a common way to remove falsy values:
const raw = ['ada', '', null, 'grace', undefined, 0, 'linus'];
const clean = raw.filter(Boolean);
console.log(clean); // ['ada', 'grace', 'linus']Be careful here: filter(Boolean) also drops 0 and '', which may be valid data. If you only want to remove null and undefined, say so directly with filter(x => x != null).
Using the Index and Array Arguments
The predicate also receives the index and the whole array. A short way to remove duplicates is to keep an element only at the first index where it appears:
const tags = ['js', 'css', 'js', 'html', 'css'];
const unique = tags.filter((tag, i, arr) => arr.indexOf(tag) === i);
console.log(unique); // ['js', 'css', 'html']This does O(n²) work because indexOf scans the array each time. For large arrays, [...new Set(tags)] is faster.
Common Errors
Forgetting return in a block body. With braces, the arrow function returns undefined, which is falsy, so nothing is kept:
const scores = [40, 75, 90];
const wrong = scores.filter(s => { s >= 60; });
const right = scores.filter(s => { return s >= 60; });
console.log(wrong); // []
console.log(right); // [75, 90]Expecting a copy of the objects. filter returns a new array, but the objects inside it are the same objects as in the original array. Mutating one affects both:
const users = [{ name: 'Ada', admin: true }, { name: 'Linus', admin: false }];
const admins = users.filter(u => u.admin);
admins[0].name = 'Ada L.';
console.log(users[0].name); // 'Ada L.'Using filter to find one item. filter(...)[0] checks every element even after it finds a match. A later chapter covers find, which stops at the first match.
Sparse arrays. filter skips holes, so [1, , 3].filter(() => true) returns [1, 3], and the result is a dense array.
Exercise
Given const products = [{ name: 'pen', stock: 0 }, { name: 'ink', stock: 12 }, { name: 'pad', stock: 3 }];, write a filter call that returns only products in stock. Then explain what products.filter(p => { p.stock > 0 }) returns and why.
Show answer
products.filter(p => p.stock > 0) returns the ink and pad objects. The braced version returns [] because the block body has no return. Every call returns undefined, which is falsy, so no element is kept.
Exercise
Why might [0, 1, 2, '', 'a'].filter(Boolean) give the wrong result when the array holds user-entered quantities and names, and what should you write instead to drop only missing values?
Show answer
Boolean treats 0 and '' as falsy, so it removes them even though they may be real values. Use .filter(x => x != null), which removes only null and undefined.