Skip to content
jshacks.dev
Fundamentals

JavaScript Array filter Method Beyond Removing Falsy Values

Array filter() keeps the items that pass a test, but filter(Boolean) also drops zero and empty strings, and async tests keep everything. Learn the safe forms.

6 min read
Summarize in AI
Flat illustration of a request passing through layers of middleware, with the JavaScript, Express and NestJS logos.

filter() is the first array method most people learn and the one most often used with a shortcut that quietly drops good data. The shortcut is arr.filter(Boolean), which reads as "remove the empty ones" and removes 0 along with them. A report that loses its zero-sales rows and a form that drops an empty string the user meant to keep come from the same line. This post covers the behavior of filter() on Node.js 24, the places it misleads, and the forms we use instead. For the surrounding language, the complete guide to modern JavaScript is the map, and the list of truthy and falsy values explains what the shortcut removes.

The core behavior is short. The callback runs for each item, and items whose result is truthy go into a new array.

JavaScript
const temperatures = [18, 25, 31, 9, 27];

const warm = temperatures.filter((degrees) => degrees >= 25);

console.log(warm);
console.log(temperatures);
Text
[ 25, 31, 27 ]
[ 18, 25, 31, 9, 27 ]

The source array is unchanged, and the result preserves the original order. The callback receives (value, index, array), so a position or a neighbor is always available without a counter.

The new array holds the same objects

filter() makes a new array and does not copy what is in it. For primitives that makes no difference. For objects it means the result and the source share members.

JavaScript
const users = [
  { id: 1, name: "Ada", active: true },
  { id: 2, name: "Grace", active: false },
];

const active = users.filter((user) => user.active);

console.log(active[0] === users[0]);

active[0].name = "Ada Lovelace";
console.log(users[0].name);
Text
true
Ada Lovelace

Editing the filtered item edited the original. This is rarely a bug when you read, and often one when you treat the result as a private copy. If a function returns a filtered list to a caller that might edit it, either document that the objects are shared or map each one to a copy. The post on shallow versus deep copies covers the options.

filter(Boolean) removes more than you think

Boolean as a callback converts each value to true or false, and the falsy list is longer than "empty": false, 0, -0, 0n, "", null, undefined and NaN.

JavaScript
const values = [0, 1, "", "a", null, undefined, false];

console.log(values.filter(Boolean));
console.log(values.filter((value) => value != null));
Text
[ 1, 'a' ]
[ 0, 1, '', 'a', false ]

The first line removed 0, "" and false along with null and undefined. NaN would have gone too. The second removed only the two nullish values, which is what most "clean up the missing entries" code means. We use value != null here on purpose, even though a style rule may forbid != elsewhere, because it is the one place where loose equality says exactly "null or undefined". A stricter spelling is value !== null && value !== undefined, and it is longer for the same result. The post on loose equality explains why != null is the single accepted idiom.

Where the data is numbers, the difference costs real values. A chart that filters a series with filter(Boolean) before plotting drops every day with zero sales, and the x axis shifts. The bug is visible only when someone compares the chart with the table.

Deduplicating with the index argument

The third argument gives access to the whole array, and the second to the position, so a filter can ask "does this value appear earlier in the list".

JavaScript
const tags = ["a", "b", "a", "c", "b"];

const unique = tags.filter((tag, index, all) => all.indexOf(tag) === index);

console.log(unique);
console.log([...new Set(tags)]);
Text
[ 'a', 'b', 'c' ]
[ 'a', 'b', 'c' ]

Both give the same answer. The indexOf version scans the array again for each item, so its work grows with the square of the length. For a hundred tags that is invisible, for a hundred thousand it is the slow line in a profile. A Set does the same job in one pass, and we use it unless the items are objects that need a custom notion of equality, where filtering on a key is the right tool.

JavaScript
const events = [
  { id: "e1", type: "click" },
  { id: "e2", type: "view" },
  { id: "e1", type: "click" },
];

const seen = new Set();
const firstOfEach = events.filter((event) => {
  if (seen.has(event.id)) return false;
  seen.add(event.id);
  return true;
});

console.log(firstOfEach.map((event) => event.id));
Text
[ 'e1', 'e2' ]

That callback has a side effect, because it records ids as it goes. That is acceptable here since the Set is local and the order of callbacks is guaranteed, but it is the reason to keep such a callback short and named.

An async callback keeps everything

The trap we cover in the every() post applies here too. An async function returns a promise, a promise is truthy, so nothing is ever filtered out.

JavaScript
const isLarge = async (size) => size > 5;

console.log([1, 7, 3, 9].filter(isLarge));
Text
[ 1, 7, 3, 9 ]

The test never had a chance. The reliable pattern resolves the tests concurrently, then filters by the results using the index.

JavaScript
const isLarge = async (size) => size > 5;
const sizes = [1, 7, 3, 9];

const verdicts = await Promise.all(sizes.map(isLarge));
const large = sizes.filter((_, index) => verdicts[index]);

console.log(large);
Text
[ 7, 9 ]

This starts every test at once. If each test is a network call, that can be a flood, and a sequential loop or a limited concurrency helper is the safer route. Order is preserved either way, because Promise.all returns results in input order.

Narrowing types in TypeScript

A filter() that removes undefined should give back an array without undefined in its type. Historically it did not, because the compiler could not see through the callback. Since TypeScript 5.5, simple checks like (x) => x !== undefined are inferred as type predicates, so the result narrows. For anything more complex you write the predicate yourself.

TypeScript
type Row = { id: number; label?: string };

const rows: Row[] = [{ id: 1, label: "a" }, { id: 2 }];

const labeled = rows.filter(
  (row): row is Row & { label: string } => row.label !== undefined,
);

const labels: string[] = labeled.map((row) => row.label);

The row is Row & { label: string } annotation tells the compiler what a true result proves. Write predicates only where the logic is a plain check, because the compiler trusts you, and a predicate that lies produces a type error that never appears.

Chaining with map, and the cost of two passes

Most real uses pair filter() with map(): keep the rows that matter, then reshape them. Each method walks the array once, so the pair walks it twice and allocates an intermediate array between them.

JavaScript
const orders = [
  { id: "o1", total: 40, status: "paid" },
  { id: "o2", total: 15, status: "refunded" },
  { id: "o3", total: 90, status: "paid" },
];

const paidTotals = orders
  .filter((order) => order.status === "paid")
  .map((order) => order.total);

console.log(paidTotals);
console.log(paidTotals.reduce((sum, total) => sum + total, 0));
Text
[ 40, 90 ]
130

For three orders the second pass is free. For a list of several hundred thousand, the intermediate array is the memory you notice, and it is the reason flatMap() or an iterator chain exists. We keep the two-step form until a profile points at it, because it reads as the sentence you would say: the paid orders, then their totals. Merging them into one reduce() saves a pass and costs the reader a callback that does two jobs.

A useful property of the chain is that filter() before map() means the mapper runs on fewer items. If the mapping is expensive, put the filter first, always.

When filter is the wrong tool

If you want one item, filter(...)[0] tests every element and builds an array to throw away. find() stops at the first match and returns it directly. If you want to transform and remove in one pass, flatMap() can return an empty array to drop an item, which avoids a second loop. If the list is large and you chain several filters, an iterator helper chain on Node.js 22 and later processes items one at a time and never builds the intermediate arrays.

filter() also should not be used for side effects. A callback that logs, counts or pushes to another array makes the result a by-product, and readers cannot tell which part is the point. Use forEach() or a loop for effects and keep the filter pure.

The method is specified as Array.prototype.filter, and the MDN page for filter lists the callback's parameters and the sparse array behavior.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.