Skip to content
jshacks.dev
Async

The RxJS filter Operator Explained With Examples

Learn how the RxJS filter operator passes only values that match a predicate, with index, type guards, distinct values and the mistakes that drop data.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, Redis, RabbitMQ and Apache Kafka logos.

Where map changes each value, filter decides which values continue. You give it a predicate, a function that returns true or false, and only the emissions for which it returns true reach the next step. Everything else is dropped silently. The idea is the same as Array.prototype.filter, applied to values that arrive over time, and it appears in nearly every real pipeline: ignore empty search text, skip events from disabled buttons, keep messages of a certain type. This post explains filter in RxJS 7 with printed output, covers the predicate's arguments, the way TypeScript narrows types through a type guard, how filter combines with map, distinctUntilChanged and takeWhile, and the three mistakes that cause confusing bugs: forgetting that dropped values are gone, using a truthiness check that drops legitimate zeros and expecting filter to stop the stream.

The basic behavior

JavaScript
import { of } from "rxjs";
import { filter } from "rxjs/operators";

of(1, 2, 3, 4, 5, 6)
  .pipe(filter((n) => n % 2 === 0))
  .subscribe((value) => console.log(value));
Text
2
4
6

Three of the six values passed. The odd ones were consumed by filter and never emitted downstream. The source still ran to completion, and so does the filtered observable, which completes when the source does. A subscriber that gets no value at all is also fine: if the predicate rejects everything, the subscription simply completes with no emissions.

JavaScript
import { of } from "rxjs";
import { filter } from "rxjs/operators";

of(1, 3, 5)
  .pipe(filter((n) => n % 2 === 0))
  .subscribe({
    next: (value) => console.log("value:", value),
    complete: () => console.log("complete, nothing emitted"),
  });
Text
complete, nothing emitted

The predicate arguments

The predicate receives the value and the zero-based index of the emission, counted over the source values, not over the passed ones.

JavaScript
import { of } from "rxjs";
import { filter } from "rxjs/operators";

of("a", "b", "c", "d", "e")
  .pipe(filter((letter, index) => index % 2 === 0))
  .subscribe((value) => console.log(value));
Text
a
c
e

The index counts every value that arrives at filter, whether or not it passes, so it identifies the position in the source. Use it for things like "every other emission" or "skip the first three", though skip(3) says the latter more directly.

Filtering objects

JavaScript
import { of } from "rxjs";
import { filter, map } from "rxjs/operators";

const orders = of(
  { id: 1, status: "paid", total: 40 },
  { id: 2, status: "refunded", total: 15 },
  { id: 3, status: "paid", total: 25 },
);

orders
  .pipe(
    filter((order) => order.status === "paid"),
    map((order) => order.total),
  )
  .subscribe((total) => console.log(total));
Text
40
25

Filtering before mapping is cheaper and clearer: the projection only runs for values that matter. A rule of thumb is to put filter as early in the pipeline as the data allows.

Type guards narrow the type

In TypeScript, a predicate declared as a type guard changes the observable's element type.

TypeScript
import { of } from "rxjs";
import { filter } from "rxjs/operators";

const mixed = of(1, "two", 3, "four");

const numbers = mixed.pipe(
  filter((value): value is number => typeof value === "number"),
);
// numbers: Observable<number>

Without the value is number annotation, the result would still be Observable<string | number>, and a later map((n) => n.toFixed()) would fail to compile. The same pattern removes null and undefined.

TypeScript
function isPresent<T>(value: T | null | undefined): value is T {
  return value !== null && value !== undefined;
}

const clean = of(1, null, 2, undefined).pipe(filter(isPresent));
// clean: Observable<number>

Writing filter(Boolean) works at runtime and does not narrow the type in all versions, and it also drops 0, "" and false, which is the second trap below.

Mistake 1: truthiness drops valid zeros

JavaScript
import { of } from "rxjs";
import { filter } from "rxjs/operators";

of(0, 1, 2, "", "x", false, null)
  .pipe(filter(Boolean))
  .subscribe((value) => console.log(JSON.stringify(value)));
Text
1
2
"x"

The 0, the empty string and false are real values that were dropped as falsy. If your stream carries numbers where zero is meaningful, such as a counter or a price, write the predicate explicitly: filter((n) => n !== null) or the isPresent helper above.

Mistake 2: expecting filter to stop the stream

filter only skips values. It does not end the stream. A subscription on an infinite source stays alive forever, even if the predicate will never pass again.

JavaScript
import { interval } from "rxjs";
import { filter, take } from "rxjs/operators";

interval(10)
  .pipe(
    filter((n) => n % 2 === 0),
    take(3),
  )
  .subscribe({
    next: (value) => console.log(value),
    complete: () => console.log("complete"),
  });
Text
0
2
4
complete

Without take(3), the interval would run until you unsubscribe. Use take, takeWhile or takeUntil when you want the stream to end. The difference between filter and takeWhile is that takeWhile(predicate) completes the stream at the first value that fails the predicate, while filter keeps going and waits for the next match.

JavaScript
import { of } from "rxjs";
import { takeWhile } from "rxjs/operators";

of(1, 2, 3, 10, 4, 5)
  .pipe(takeWhile((n) => n < 5))
  .subscribe((value) => console.log(value));
Text
1
2
3

takeWhile stopped at 10 and never looked at 4 or 5, which a filter((n) => n < 5) would have let through.

Mistake 3: a stateful predicate

A predicate that depends on outside state gives different answers to different subscribers or different runs. Keep it a pure function of its arguments. If you need to remember previous values, use an operator built for it.

JavaScript
import { of } from "rxjs";
import { distinctUntilChanged } from "rxjs/operators";

of(1, 1, 2, 2, 2, 3, 1)
  .pipe(distinctUntilChanged())
  .subscribe((value) => console.log(value));
Text
1
2
3
1

distinctUntilChanged drops a value equal to the previous one, which is a filter with memory, and it takes an optional comparison function for objects. It is the standard companion for search boxes and form controls, where the same text can be emitted twice in a row.

A realistic pipeline: search input

JavaScript
import { of } from "rxjs";
import { filter, map, distinctUntilChanged } from "rxjs/operators";

const keystrokes = of("j", "ja", "ja ", "jav", "", "java");

keystrokes
  .pipe(
    map((text) => text.trim()),
    filter((text) => text.length >= 2),
    distinctUntilChanged(),
  )
  .subscribe((query) => console.log("search for:", query));
Text
search for: ja
search for: jav
search for: java

The pipeline trims the text, skips queries shorter than two characters and drops repeats. The "ja " value became "ja" after trimming, and distinctUntilChanged dropped it as a repeat of the previous query. In a real component the source would be an input event stream with debounceTime before the filter, so a request fires only after the user pauses.

OperatorBehavior
filter(fn)Passes values for which fn returns true
take(n)Passes the first n values, then completes
skip(n)Drops the first n values
first(fn)Emits the first match, then completes; errors if none
takeWhile(fn)Passes values until fn is false, then completes
distinctUntilChanged()Drops consecutive duplicates
ignoreElements()Drops everything, keeps only completion and errors

Reading a pipeline with filters

A useful exercise when reading someone else's RxJS code is to annotate how many values survive each step. Start with the source and write down roughly how often it emits. After a filter, ask what fraction is dropped, and whether anything downstream depends on seeing every value. Typical bugs appear at this boundary: a counter that is incremented in a tap after a filter and so misses the dropped events, a UI that expects a value on every keystroke but only gets the long ones, or a form that never shows a validation message because the filter removed the empty value that would have triggered it.

If you find yourself writing a filter with several conditions joined by && and ||, extract it into a named predicate function and test it on its own. Predicates are pure, small and easy to table-test, and the pipeline then says what it does, for example filter(isPublishedOrder), instead of how it decides. When the same predicate is needed on both an observable and an array, you also get to use it in both places.

Where filter belongs in a pipeline

Place filter as close to the source as the logic allows, because every operator after it runs for fewer values, and because a reader sees the conditions that define the stream before any transformation. The exception is a filter that depends on a derived value, such as a trimmed or parsed string, which must come after the map that produces it. When two filters are next to each other, you can combine them into one predicate without any change in behavior, and doing so usually reads better than a pair of one-line filters.

Finally, keep an eye on what the subscriber expects. If the consumer needs a value at least once, such as an initial state for a form, a filter that can drop everything is a bug waiting for a rare input. Use startWith to supply a default, or defaultIfEmpty to emit one value when the filtered stream completes without any, so the subscriber is never left waiting for a first value that will not come.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

6 min read

Get new posts by email

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

Unsubscribe in one click. No spam, ever.