Skip to main content

What does filter() do?

The filter() operator in RxJS lets through only the values from the stream that pass a check.


A simple example:

ts
import { of } from 'rxjs'; import { filter } from 'rxjs/operators'; of(1, 2, 3, 4, 5) .pipe(filter(x => x % 2 === 0)) .subscribe(val => console.log(val));

The stream was: 1 → 2 → 3 → 4 → 5 What remains: 2 → 4


How it works:

  • Each value is checked by the function (the condition)
  • If true, it passes through
  • If false, it's ignored

Where it's used:

  • Keep only the values you need from a stream
  • Remove empty strings, zeros, errors
  • React only to certain events

Example in Angular:

ts
this.searchInput.valueChanges .pipe(filter(value => value.length > 2)) .subscribe(search => { // Run the search only if more than 2 characters were entered });

Conclusion:

filter() is like a checkpoint in the stream: it only lets through the data that fits what you need. Everything else is cut off.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.