Sub topic 9
Keeping What Matches with filter
This chapter assumes you know arrow functions, truthy and falsy values, and the (element, index, array) callback signature covered earlier. It also assumes you know that some array methods change the original array and others return a new one.
filter answers one question: "Which elements should I keep?" You pass it a function called a predicate, which takes an element and returns a value that JavaScript reads as true or false. filter calls the predicate once for each element. It returns a new array holding every element for which the predicate returned a truthy value, in the original order.
The basic shape
const scores = [72, 95, 58, 88, 41];
const passing = scores.filter(score => score >= 60);
console.log(passing); // [72, 95, 88]
console.log(scores); // [72, 95, 58, 88, 41] (unchanged)These rules always hold:
filternever mutates the array it is called on.- The result has the same length as the input or is shorter. It is never longer.
- Elements keep their relative order.
- If nothing matches, you get an empty array
[], neverundefinedornull. You can safely call.lengthor other methods on the result.
Filtering objects
In real code you mostly filter arrays of objects by one of their properties.
const tasks = [
{ id: 1, title: 'Write report', done: true, priority: 'high' },
{ id: 2, title: 'Email Sam', done: false, priority: 'low' },
{ id: 3, title: 'Fix login bug', done: false, priority: 'high' }
];
const openHighPriority = tasks.filter(
task => !task.done && task.priority === 'high'
);
console.log(openHighPriority);
// [{ id: 3, title: 'Fix login bug', done: false, priority: 'high' }]When a predicate grows past one condition, give it a name. A named predicate documents your intent and can be reused anywhere:
const isOpen = task => !task.done;
const isHigh = task => task.priority === 'high';
const tasks = [
{ id: 1, done: true, priority: 'high' },
{ id: 2, done: false, priority: 'low' },
{ id: 3, done: false, priority: 'high' }
];
console.log(tasks.filter(isOpen).length); // 2
console.log(tasks.filter(t => isOpen(t) && isHigh(t))); // [{ id: 3, done: false, priority: 'high' }]Removing an item without mutation
filter is the usual way to "delete" an item when you must not touch the original array, as with React state or Redux reducers. You keep everything except the item you want gone:
const cart = [
{ sku: 'A1', qty: 2 },
{ sku: 'B7', qty: 1 },
{ sku: 'C3', qty: 4 }
];
const withoutB7 = cart.filter(item => item.sku !== 'B7');
console.log(withoutB7.map(i => i.sku)); // ['A1', 'C3']
console.log(cart.length); // 3Compare this with splice, which removes in place and needs you to find the index first. filter also removes every match, not only the first one. That is usually what you want with duplicates, and occasionally it is not.
The result is a shallow copy
The new array is a new container, but the objects inside it are the same objects as in the original. filter does not clone them.
const products = [
{ name: 'Lamp', inStock: true },
{ name: 'Desk', inStock: false }
];
const available = products.filter(p => p.inStock);
available[0].name = 'Floor lamp';
console.log(products[0].name); // 'Floor lamp'
console.log(available[0] === products[0]); // trueCommon errors
Forgetting to return inside braces
An arrow function with a block body { ... } needs an explicit return. Without one, the predicate returns undefined. That value is falsy, so filter quietly drops everything.
const nums = [1, 2, 3, 4];
const wrong = nums.filter(n => { n % 2 === 0; });
console.log(wrong); // []
const right = nums.filter(n => { return n % 2 === 0; });
console.log(right); // [2, 4]
const concise = nums.filter(n => n % 2 === 0);
console.log(concise); // [2, 4]An empty result where you expected matches is the usual sign of this bug.
Truthiness surprises and filter(Boolean)
The predicate does not have to return a real boolean. Any return value is coerced. That is why filter(Boolean) is a popular shortcut for removing "empty" values:
const values = [0, 1, '', 'hi', null, undefined, NaN, false, []];
console.log(values.filter(Boolean)); // [1, 'hi', []]The shortcut drops 0, '', and NaN along with null and undefined. If zero or an empty string is valid data, say exactly what you want to drop:
const counts = [0, 3, null, 5, undefined];
console.log(counts.filter(Boolean)); // [3, 5] (the 0 is lost)
console.log(counts.filter(n => n != null)); // [0, 3, 5]n != null uses loose inequality on purpose. It is true for everything except null and undefined. Also note that [] and {} are truthy, so filter(Boolean) keeps empty arrays and objects.
Using filter when you want one element
filter always walks the entire array and always returns an array. If you need only the first match, find stops early and returns the element itself. Writing users.filter(u => u.id === 7)[0] works, but it does extra work and hides your intent.
| Goal | Method | Returns | Stops early? | Mutates? |
|---|---|---|---|---|
| All matching elements | `filter` | new array (maybe empty) | no | no |
| First matching element | `find` | element or `undefined` | yes | no |
| Whether any element matches | `some` | boolean | yes | no |
| Remove elements in place | `splice` | removed elements | n/a | yes |
Using the index and array arguments
The predicate receives (element, index, array), the same as other callback methods. The index lets you filter by position:
const rows = ['header', 'r1', 'r2', 'r3', 'r4'];
const body = rows.filter((_, i) => i > 0);
const everyOther = rows.filter((_, i) => i % 2 === 0);
console.log(body); // ['r1', 'r2', 'r3', 'r4']
console.log(everyOther); // ['header', 'r2', 'r4']The third argument lets the predicate compare an element with the rest of the array. A classic use is removing duplicates by keeping only the first occurrence of each value:
const tags = ['js', 'css', 'js', 'html', 'css'];
const unique = tags.filter((tag, i, arr) => arr.indexOf(tag) === i);
console.log(unique); // ['js', 'css', 'html']
console.log([...new Set(tags)]); // ['js', 'css', 'html']The indexOf version is O(n²) because it searches the array again for every element. For primitives, new Set is linear and clearer. The filter pattern still helps when you need a custom notion of "duplicate", such as objects with the same id. In that case, track the IDs you have already seen in a Set inside the predicate.
Edge cases
Sparse arrays
filter skips holes. It does not call the predicate for missing indexes, so the result is always dense:
const sparse = [1, , 3, , 5];
console.log(sparse.length); // 5
const dense = sparse.filter(() => true);
console.log(dense); // [1, 3, 5]
console.log(dense.length); // 3A slot holding undefined explicitly is not a hole. It is passed to the predicate like any other value.
Changing the array during filtering
filter fixes the range it will visit before the first call. If the predicate pushes new elements, they are not visited. If it changes an element that has not been reached yet, the predicate sees the new value. Code like this is hard to reason about. Keep predicates pure: they should read their arguments, return a decision, and change nothing.
Exercise
Given const readings = [12, 0, null, 7, undefined, 0, 3];, write one filter call that removes only null and undefined and keeps the zeros. What does it return, and what would readings.filter(Boolean) return instead?
Show answer
readings.filter(r => r != null) returns [12, 0, 7, 0, 3]. readings.filter(Boolean) returns [12, 7, 3] because 0 is falsy and gets dropped along with null and undefined.
Exercise
This code is meant to keep users who are 18 or older, but adults is always empty: const adults = users.filter(u => { u.age >= 18 });. Explain the bug and fix it. Then explain why adults[0].age = 99 would also change the matching object in users.
Show answer
The arrow function has a block body without return, so it returns undefined for every user, and filter keeps nothing. Fix it with users.filter(u => u.age >= 18) or users.filter(u => { return u.age >= 18; }). filter makes a shallow copy: the new array holds references to the same user objects, so changing a property through adults[0] changes the object that users also references.
Exercise
Write a filter call that removes duplicate objects by id from const items = [{ id: 1 }, { id: 2 }, { id: 1 }, { id: 3 }]; and keeps the first occurrence of each, in linear time.
Show answer
const seen = new Set(); const unique = items.filter(item => { if (seen.has(item.id)) return false; seen.add(item.id); return true; }); gives [{ id: 1 }, { id: 2 }, { id: 3 }]. Each element costs one Set lookup, so the whole pass is O(n). This predicate depends on outside state (seen), so create a new Set each time you run it.