Skip to content
filtering

filter

Emits only the values that pass a given predicate function — all others are silently dropped.

Signature

filter<T>(predicate: (value: T, index: number) => boolean): MonoTypeOperatorFunction<T>

Marble Diagram

source:  --1----2----3----4----|
filter(x => x % 2 === 0)
result:  -------2---------4----|

Example

import { from } from 'rxjs'
import { filter } from 'rxjs/operators'

from([1, 2, 3, 4, 5]).pipe(
  filter(x => x % 2 === 0)
).subscribe(console.log)
// Output: 2, 4

Common Use Cases

  • Ignore empty or null values from a stream
  • Filter user keystrokes (e.g. only act on Enter key)
  • Gate events by permission or feature flag

Flow Diagram