filter
filter builds a new array holding only the items your test returns true for, which is how you narrow a list down.
filter calls a test function per item and keeps the ones that answer truthy. The result can be shorter than the original, or empty. It never changes the source array and never transforms the items it keeps.
EXERCISE
1Keeping What Passes a Test
Where map transforms every item, filter decides which items survive and leaves them exactly as they were.
The shape:
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 ] <- untouched
Six in, three out. The callback answered true three times.
The callback is a question, and the answer decides:
const numbers = [1, 2, 3];
numbers.filter((n) => {
const keep = n > 1;
console.log(`${n}: ${keep}`);
return keep;
});
// 1: false dropped
// 2: true kept
// 3: true kept
Filtering objects, which is the everyday use:
const users = [
{ name: "Ada", age: 36, active: true },
{ name: "Grace", age: 45, active: false },
{ name: "Alan", age: 41, active: true },
];
const activeUsers = users.filter((user) => user.active);
console.log(activeUsers.length); // 2
const overForty = users.filter((user) => user.age > 40);
console.log(overForty.map((u) => u.name)); // [ 'Grace', 'Alan' ]
Nothing matching gives an empty array, not undefined:
const found = users.filter((user) => user.age > 100);
console.log(found); // []
console.log(found.length); // 0
console.log(Array.isArray(found)); // true
if (found.length === 0) {
console.log("No matches");
}
filter always hands back an array, even when nothing matched, which means you can safely call .length or chain another method onto it without checking first. That is a real convenience compared to find in two lessons' time, which returns undefined when nothing matches and does need checking.
EXERCISE
2Truthy Tests and Common Filters
The callback's answer is judged for truthiness, not strict equality with true, which makes several short forms possible.
Any truthy value keeps the item:
const values = ["a", "", "b", null, "c", 0];
const nonEmpty = values.filter((v) => v);
console.log(nonEmpty); // [ 'a', 'b', 'c' ]
// The callback returned the value itself.
// "" , null and 0 are falsy, so those three were dropped.
Which gives the shortest possible cleanup:
const messy = [1, null, 2, undefined, 3, ""];
console.log(messy.filter(Boolean)); // [ 1, 2, 3 ]
// Boolean is called with each item and returns true or false.
Be careful with that one: it also drops a legitimate 0 or "".
Filtering with a search term:
const titles = ["Dune", "The Hobbit", "Brave New World"];
function search(query) {
const q = query.trim().toLowerCase();
return titles.filter((title) => title.toLowerCase().includes(q));
}
console.log(search(" THE ")); // [ 'The Hobbit' ]
console.log(search("o")); // [ 'The Hobbit', 'Brave New World' ]
Removing one item by id:
const todos = [
{ id: 1, text: "Buy milk" },
{ id: 2, text: "Call Sam" },
{ id: 3, text: "Pay bill" },
];
const remaining = todos.filter((todo) => todo.id !== 2);
console.log(remaining.length); // 2
console.log(todos.length); // 3 <- original intact
That last pattern is how removal is done throughout modern : build a new list without the item, rather than cutting the item out of the old one.
Pro Tip:
filter(Boolean)is a useful idiom and a trap at the same time. For strippingnullandundefinedout of a list of objects it is perfect. For a list of numbers or strings it silently removes every0and every empty string, which are often real values you meant to keep.
EXERCISE
3filter with map, and Keeping Both Halves
Filtering and mapping together covers most list work, and two small details are worth knowing before you rely on it.
The standard pairing:
const products = [
{ name: "Tea", price: 40, inStock: true },
{ name: "Coffee", price: 120, inStock: false },
{ name: "Cocoa", price: 90, inStock: true },
];
const availableNames = products
.filter((p) => p.inStock)
.map((p) => p.name);
console.log(availableNames); // [ 'Tea', 'Cocoa' ]
filter gives you the index too:
const letters = ["a", "b", "c", "d"];
const everyOther = letters.filter((letter, i) => i % 2 === 0);
console.log(everyOther); // [ 'a', 'c' ]
Keeping both halves needs two passes:
const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter((n) => n % 2 === 0);
const odds = numbers.filter((n) => n % 2 !== 0);
console.log(evens); // [ 2, 4 ]
console.log(odds); // [ 1, 3, 5 ]
// Two passes over five items costs nothing.
// For a very large array you would write one loop instead.
filter never transforms, which is the rule to hold on to:
const numbers = [1, 2, 3];
// This does not double anything. It keeps items where n * 2 is truthy,
// which is all of them, since every result is non-zero.
console.log(numbers.filter((n) => n * 2)); // [ 1, 2, 3 ]
// Transforming is map's job:
console.log(numbers.map((n) => n * 2)); // [ 2, 4, 6 ]
The distinction is worth stating plainly: map changes the items and keeps the count, filter changes the count and keeps the items. When you need both, chain them, and put the filter first so the map has less to do and the full object to work from.
