Sub topic 5
filter: Keeping Only What Matches
This chapter assumes you can write arrow functions, know what truthy and falsy values are, and have read the earlier chapters on callbacks, callback arguments, and map. filter follows the same calling convention as map. The difference is what it does with your callback's return value: map stores that value, while filter uses it to decide whether the original element stays.
The working model
Array.prototype.filter(predicate, thisArg?) creates a new empty array. It walks the source array from index 0 upward and calls predicate(element, index, array) for each element. When the predicate returns a truthy value, filter pushes the original element onto the new array. When it returns a falsy value, the element is skipped. At the end, filter returns the new array.
A predicate is a function that answers a yes-or-no question about one element. Its name usually reads like a question: isActive, hasStock, isEven.
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)Three properties follow from this model:
- The result's length is anywhere from 0 to the source length.
filternever adds elements, and it never changes them. - Elements keep their original relative order.
- The source array is not modified by
filteritself.
Truthy, not true
filter does not require a boolean. It converts whatever the predicate returns to a boolean, using the same rules as if. This is convenient, and it also causes some quiet bugs.
| Predicate returns | Element kept? |
|---|---|
| `true`, `1`, `'no'`, `[]`, `{}` | Yes |
| `false`, `0`, `''`, `null`, `undefined`, `NaN` | No |
| A Promise (from an `async` predicate) | Yes, always |
The last row matters. An async function always returns a Promise, and a Promise is an object, so every element passes. A later chapter covers async callbacks. For now, remember that filter does not wait for a promise to settle.
The common idiom filter(Boolean) builds on these rules. Boolean is itself a function that returns true or false, so you can pass it directly to drop every falsy value:
const raw = [0, 'a', '', null, 'b', undefined, NaN, false];
console.log(raw.filter(Boolean)); // ['a', 'b']Using the index and array arguments
Most predicates only look at the element. The second and third arguments help when the decision depends on position or on the other elements.
const letters = ['a', 'b', 'c', 'd', 'e'];
// Keep every other element by position
console.log(letters.filter((_, i) => i % 2 === 0)); // ['a', 'c', 'e']
// Keep elements that differ from their predecessor
const readings = [3, 3, 4, 4, 4, 2, 3];
const changes = readings.filter((v, i, arr) => i === 0 || v !== arr[i - 1]);
console.log(changes); // [3, 4, 2, 3]A well-known deduplication idiom keeps an element only if this is 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 idiom has two problems. It runs in O(n²) time, because indexOf scans the array again for every element. It also deletes every NaN: indexOf uses strict equality, NaN !== NaN, so indexOf(NaN) returns -1 and never equals the index.
console.log([1, NaN, NaN].filter((x, i, a) => a.indexOf(x) === i)); // [1]
console.log([...new Set([1, NaN, NaN])]); // [1, NaN]Use a Set for deduplicating primitives. Use the filter idiom only when you need a custom notion of "same", and in that case compare with findIndex.
A new array, but the same objects
filter returns a new array, but the array is a shallow copy. The elements it keeps are the same object references as in the source, not clones.
const users = [
{ name: 'Ada', active: true },
{ name: 'Linus', active: false }
];
const active = users.filter(u => u.active);
console.log(active === users); // false (different arrays)
console.log(active[0] === users[0]); // true (same object)
active[0].name = 'Ada Lovelace';
console.log(users[0].name); // 'Ada Lovelace'You can reorder or truncate active without affecting users. If you modify an object inside it, the change also appears in users. If downstream code edits the results, copy the objects with map(u => ({ ...u })) after filtering.
This behavior is what makes filter the standard non-mutating way to "remove" items, a common need in UI state updates:
const todos = [
{ id: 1, text: 'write' },
{ id: 2, text: 'review' },
{ id: 3, text: 'ship' }
];
const withoutTwo = todos.filter(todo => todo.id !== 2);
console.log(withoutTwo.map(t => t.id)); // [1, 3]
console.log(todos.length); // 3Compare this with splice, which modifies the array in place and requires you to find the index first.
Edge cases the spec defines
Holes are skipped
A sparse array contains holes, which are indexes that were never assigned. filter does not call the predicate for holes, and the holes do not appear in the result. As a result, the output is always dense:
const sparse = [1, , 3];
const seen = [];
const out = sparse.filter((x, i) => { seen.push(i); return true; });
console.log(out); // [1, 3]
console.log(seen); // [0, 2] (index 1 was never visited)
console.log(out.length); // 2An explicit undefined is not a hole. It is visited and passed to the predicate like any other value.
The length is fixed at the start
filter reads the array's length once, before the first call. If the predicate changes the source array during iteration, these rules apply:
- Elements appended during the call are not visited.
- Elements changed before
filterreaches them are seen with their new values. - Elements deleted before
filterreaches them are treated as holes and skipped.
const arr = [1, 2, 3];
const result = arr.filter((n, i, a) => {
if (i === 0) a.push(99);
return true;
});
console.log(result); // [1, 2, 3]
console.log(arr); // [1, 2, 3, 99]These rules exist so that mutation cannot cause an infinite loop. Don't write code that depends on them. A predicate that modifies the array it is filtering will confuse whoever reads it next.
thisArg and arrow functions
The optional second argument sets this inside the predicate. It only works with function expressions, because arrow functions ignore it and take this from the surrounding scope:
const range = { min: 3 };
console.log([1, 2, 3, 4].filter(function (n) { return n >= this.min; }, range)); // [3, 4]Modern code usually captures the value in a closure: const min = 3; nums.filter(n => n >= min). A closure is clearer and works with arrows.
Common errors
Missing return in a block body
An arrow function with braces needs an explicit return. Without one it returns undefined, which is falsy, so every element is dropped:
const nums = [1, 2, 3, 4];
console.log(nums.filter(n => { n > 2; })); // []
console.log(nums.filter(n => { return n > 2; })); // [3, 4]
console.log(nums.filter(n => n > 2)); // [3, 4]An empty result where you expected matches almost always means the predicate is returning undefined.
Assignment instead of comparison
u => u.role = 'admin' assigns the string to every user and returns 'admin'. That value is truthy, so every element passes and the source objects are now corrupted. Use ===. A linter rule such as no-return-assign catches this mistake.
Using filter when you want one element
filter always scans the whole array and always returns an array. If you need the first match, filter(...)[0] wastes work and hides the "not found" case as undefined from an empty array. find stops at the first match. A later chapter covers it along with some and every.
Using filter for side effects
If the predicate logs, counts, or sends requests and you ignore the returned array, use forEach or a loop. Keep predicates pure: the same element should always give the same answer.
Composing predicates
Predicates are ordinary functions, so you can name them, reuse them, and combine them:
const products = [
{ name: 'pen', price: 2, inStock: true },
{ name: 'lamp', price: 40, inStock: false },
{ name: 'mug', price: 9, inStock: true },
{ name: 'desk', price: 150, inStock: true }
];
const inStock = p => p.inStock;
const under = max => p => p.price < max;
const both = (f, g) => x => f(x) && g(x);
const not = f => x => !f(x);
console.log(products.filter(both(inStock, under(10))).map(p => p.name)); // ['pen', 'mug']
console.log(products.filter(not(inStock)).map(p => p.name)); // ['lamp']under(10) is a function that returns a predicate. This lets you write the threshold once without hard-coding it into many small lambdas. When you combine conditions inside one predicate with &&, put the cheapest or most selective check first, because && short-circuits.
Exercise
What does [0, 1, '', 'x', null, [], {}].filter(v => v) return, and why does [] survive?
Show answer
It returns [1, 'x', [], {}]. The predicate returns each value itself, and filter keeps truthy values. Every object is truthy, empty arrays and empty objects included, so [] and {} are kept. 0, '', and null are falsy and are dropped.
Exercise
A colleague writes items.filter(item => { item.price > 0 }) and gets an empty array even though most prices are positive. Explain the cause and give two fixes.
Show answer
The arrow function has a block body with no return statement, so it returns undefined for every item. undefined is falsy, so nothing is kept. Fix it either by adding return, item => { return item.price > 0; }, or by using a concise body, item => item.price > 0.
Exercise
Given const a = [{ n: 1 }, { n: 2 }]; const b = a.filter(x => x.n > 1); b[0].n = 5; b.push({ n: 9 });, what are a and b afterward?
Show answer
a is [{ n: 1 }, { n: 5 }] and b is [{ n: 5 }, { n: 9 }]. filter returns a new array, so pushing onto b does not affect a. The kept element is the same object reference, so setting b[0].n also changes a[1].
Exercise
Why does [1, NaN, 2, NaN].filter((x, i, arr) => arr.indexOf(x) === i) lose every NaN, and what should you use instead?
Show answer
indexOf compares with strict equality, and NaN is not strictly equal to itself, so arr.indexOf(NaN) returns -1, which never equals a valid index. Use [...new Set(arr)]. Set uses SameValueZero comparison, which treats NaN as equal to NaN, so the result is [1, NaN, 2].