Sub topic 9
Keeping What Matches with filter
This chapter assumes you know arrow functions, the (element, index, array) callback signature from the callbacks chapter, and the difference between mutating and non-mutating methods.
The working model
filter calls your callback once for each element. If the callback returns a truthy value, that element goes into a new array. If it returns a falsy value, the element is left out. The original array is not changed. When nothing matches, the result is an empty array, never undefined.
const products = [
{ name: 'Lamp', price: 30, inStock: true },
{ name: 'Desk', price: 120, inStock: false },
{ name: 'Chair', price: 85, inStock: true }
];
const available = products.filter(p => p.inStock);
console.log(available.map(p => p.name)); // ['Lamp', 'Chair']
console.log(products.length); // 3 (original untouched)
const none = products.filter(p => p.price > 1000);
console.log(none); // []Using the index and array arguments
Most filters only need the element. The second and third arguments are useful when the decision depends on position or on other elements. A common example is removing duplicates by keeping only the first occurrence of each value:
const ids = [1, 2, 2, 3, 1];
const unique = ids.filter((value, index, arr) => arr.indexOf(value) === index);
console.log(unique); // [1, 2, 3]This works for small arrays. For large arrays, [...new Set(ids)] is faster, because indexOf searches the array again for every element.
Common errors
Forgetting to return
When an arrow function has a body in braces, it needs an explicit return. Without it, the callback returns undefined, which is falsy, so every element is dropped:
const items = [{ price: 30 }, { price: 120 }];
const wrong = items.filter(p => { p.price < 50; });
console.log(wrong); // []
const right = items.filter(p => { return p.price < 50; });
console.log(right); // [{ price: 30 }]Truthiness surprises
filter(Boolean) is a common way to remove empty values. It also removes 0, NaN, and false, which may be valid data:
const scores = [10, 0, null, 7, undefined, ''];
console.log(scores.filter(Boolean)); // [10, 7]
console.log(scores.filter(s => s != null)); // [10, 0, 7, '']Write the condition you mean instead of relying on truthiness.
Assuming the result is a deep copy
filter creates a new array, but the objects in it are the same objects as in the original. Changing one changes both:
const stock = [{ name: 'Lamp', price: 30 }];
const cheap = stock.filter(p => p.price < 50);
cheap[0].price = 25;
console.log(stock[0].price); // 25filter compared with related methods
| Goal | Method | Returns |
|---|---|---|
| All matching elements | `filter` | New array (possibly empty) |
| First matching element | `find` | Element or `undefined` |
| Whether any element matches | `some` | Boolean |
| Remove by position in place | `splice` | Removed elements (mutates) |
Exercise
Given const temps = [12, -3, 0, 25, -8, 0];, write one filter call that keeps only the non-negative temperatures, and explain why temps.filter(t => t) would give the wrong answer.
Show answer
temps.filter(t => t >= 0) returns [12, 0, 25, 0]. The version temps.filter(t => t) keeps every truthy value. Negative numbers are truthy, so -3 and -8 are kept, and 0 is falsy, so both zeros are dropped. The result would be [12, -3, 25, -8].
Exercise
Why does products.filter(p => { p.inStock }) return an empty array?
Show answer
The braces make the arrow function a block body. A block body has no implicit return, so the callback returns undefined for every element. undefined is falsy, so filter keeps nothing. Fix it with p => p.inStock or p => { return p.inStock; }.