filter: Keeping What Matters
filter creates a new array with only the elements where your callback returns true. Everything else is excluded.
filter returns the same or fewer elements. Chain with map for powerful data pipelines. Use .filter(Boolean) to remove all falsy values (false, 0, "", null, undefined, NaN).
EXERCISE
1filter() Keeps Elements That Pass a Test
The filter method creates a new array containing only the elements where your callback function returns true. Everything else is excluded.
filter builds a new array containing only the elements for which your function returned a truthy value. It does not modify the original array and it does not modify the elements, so the result is always the same length or shorter, holding the same values that were already there. The function you pass is called once per element and its return value is read as a yes or a no.
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]
The distinction from map is worth stating plainly: map decides what each element becomes, filter decides whether each element stays. The callback of one returns a value; the callback of the other returns a verdict.
On objects, the test is usually a property:
const users = [
{ name: "Ada", active: true },
{ name: "Alan", active: false },
{ name: "Grace", active: true },
];
const active = users.filter((u) => u.active);
console.log(active.length); // 2
The elements in active are the same objects that are in users, not copies. Changing one changes both, because filter selects references rather than duplicating what it selects.
Nothing matching is not an error:
const none = numbers.filter((n) => n > 100);
console.log(none); // []
console.log(none.length); // 0
An empty array, which is safe to iterate and safe to chain. This is the quiet advantage over an index-based search: there is no -1 to remember and no undefined to guard against.
The most common mistake is forgetting to return:
const wrong = numbers.filter((n) => {
n % 2 === 0;
});
console.log(wrong); // []
The block returns undefined, which is falsy, so every element is rejected and the result is empty. An empty array from a filter you expected to match something is almost always this, rather than a wrong condition.
filter also passes the index and the whole array to your callback, which makes positional tests possible:
const items = ["a", "b", "c", "d"];
const everyOther = items.filter((value, index) => index % 2 === 0);
console.log(everyOther); // ["a", "c"]
Using the third parameter is rarer, but it is what lets a filter compare an element against its neighbours without closing over the array separately.
EXERCISE
2Chaining filter with map
The real power shows up when you chain filter and map together. Filter first to narrow down, then map to transform. Clean, readable, no loops.
Because filter and map both return arrays, they chain. The usual order is to reduce the set first and then transform what is left, which is both clearer and less work.
const orders = [
{ item: "book", price: 12, shipped: true },
{ item: "pen", price: 2, shipped: false },
{ item: "lamp", price: 40, shipped: true },
];
const shippedPrices = orders
.filter((o) => o.shipped)
.map((o) => o.price);
console.log(shippedPrices); // [12, 40]
Read it as a sentence: keep the shipped orders, then take each price. Each line does one thing, and the name of the method says which.
Order matters for cost, and sometimes for correctness:
const a = orders.filter((o) => o.shipped).map((o) => o.price);
const b = orders.map((o) => o.price).filter((p) => p > 0);
The first filters three elements and then transforms two. The second transforms all three and then filters. With three orders this is irrelevant; with fifty thousand it is not, and filtering first is the habit worth having.
Correctness can depend on it too:
const withRatio = orders
.filter((o) => o.price > 0)
.map((o) => 100 / o.price);
Reversing those two lines would divide by zero before the guard had a chance to remove the offending element.
Chains can be longer, and stay readable as long as each step is one idea:
const names = orders
.filter((o) => o.shipped)
.filter((o) => o.price > 10)
.map((o) => o.item.toUpperCase());
console.log(names); // ["BOOK", "LAMP"]
Two separate filters rather than one condition joined by && is a deliberate choice. Each line can be read, commented or removed on its own, and when a bug appears you can delete one line to find out which condition is wrong.
The cost is an extra pass over the array. That is the right trade almost always, and knowing you made it is what matters.
One property makes chains safe to build up incrementally: each step receives a fresh array, so no step can disturb what an earlier one produced.
const shipped = orders.filter((o) => o.shipped);
const prices = shipped.map((o) => o.price);
console.log(orders.length); // 3
console.log(shipped.length); // 2
console.log(prices.length); // 2
Splitting a chain into named steps like this costs nothing at runtime and is often the fastest way to find which step is wrong.
EXERCISE
3Truthy and Falsy Values in filter
filter removes elements where the callback returns a falsy value. Understanding truthy vs falsy is essential for writing clean filter callbacks.
filter does not require your callback to return true or false. It keeps the element whenever the return value is truthy, which is every value except a specific short list.
The falsy values are false, 0, "", null, undefined, NaN and 0n. Everything else is truthy, including "0", "false", [] and {}.
const mixed = [0, 1, "", "hello", null, 42, undefined, "world", NaN, false];
const kept = mixed.filter(Boolean);
console.log(kept); // [1, "hello", 42, "world"]
filter(Boolean) is a common idiom for removing empty values. Boolean used as a function converts its argument, so each element is kept exactly when it is truthy.
This is also where the behaviour surprises people:
const values = [0, 1, 2, 3];
console.log(values.filter((n) => n)); // [1, 2, 3]
0 is falsy, so a legitimate zero is dropped. If zero is a real value in your data, the test has to be explicit:
console.log(values.filter((n) => n !== null && n !== undefined)); // [0, 1, 2, 3]
The same trap catches empty strings, which are often meaningful:
const fields = ["Ada", "", "Grace"];
console.log(fields.filter((f) => f)); // ["Ada", "Grace"]
console.log(fields.filter((f) => f !== null)); // ["Ada", "", "Grace"]
Dropping an empty string is right when you are cleaning input and wrong when the blank is an answer someone deliberately left blank.
Returning a non-boolean accidentally:
const nums = [1, 2, 3];
console.log(nums.filter((n) => n * 10)); // [1, 2, 3]
console.log(nums.filter((n) => n - 1)); // [2, 3]
Neither callback is a test, and neither is an error. The first returns 10, 20, 30, all truthy, so everything is kept. The second returns 0, 1, 2, and the zero is falsy, so the first element is dropped. Both look like conditions and neither is one.
Pro Tip: A filter that keeps everything or nothing is usually returning a value rather than a comparison. Read the callback and ask what it actually evaluates to, not what it looks like it is asking.
