rxjs / 7.5.5 / api / operators / filter.html /

filter

function stable operator

Filter items emitted by the source Observable by only emitting those that satisfy a specified predicate.

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

Parameters

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

A function that evaluates each value emitted by the source Observable. If it returns true, the value is emitted, if false the value is not passed to the output Observable. The index parameter is the number i for the i-th source emission that has happened since the subscription, starting from the number 0.

thisArg any

Optional. Default is undefined.

An optional argument to determine the value of this in the predicate function.

Returns

MonoTypeOperatorFunction<T>: A function that returns an Observable that emits items from the source Observable that satisfy the specified predicate.

Description

Like Array.prototype.filter(), it only emits a value from the source if it passes a criterion function.

filter marble diagram

Similar to the well-known Array.prototype.filter method, this operator takes values from the source Observable, passes them through a predicate function and only emits those values that yielded true.

Example

Emit only click events whose target was a DIV element

import { fromEvent, filter } from 'rxjs';

const div = document.createElement('div');
div.style.cssText = 'width: 200px; height: 200px; background: #09c;';
document.body.appendChild(div);

const clicks = fromEvent(document, 'click');
const clicksOnDivs = clicks.pipe(filter(ev => (<HTMLElement>ev.target).tagName === 'DIV'));
clicksOnDivs.subscribe(x => console.log(x));

Overloads

filter(predicate: (this: A, value: T, index: number) => value is S, thisArg: A): OperatorFunction<T, S>

Parameters

predicate (this: A, value: T, index: number) => value is S
thisArg A

Returns

OperatorFunction<T, S>

filter(predicate: (value: T, index: number) => value is S): OperatorFunction<T, S>

Parameters

predicate (value: T, index: number) => value is S

Returns

OperatorFunction<T, S>

filter(predicate: BooleanConstructor): OperatorFunction<T, TruthyTypesOf<T>>

Parameters

predicate BooleanConstructor

Returns

OperatorFunction<T, TruthyTypesOf<T>>

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

Parameters

predicate (this: A, value: T, index: number) => boolean
thisArg A

Returns

MonoTypeOperatorFunction<T>

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

Parameters

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

Returns

MonoTypeOperatorFunction<T>

See Also

© 2015–2022 Google, Inc., Netflix, Inc., Microsoft Corp. and contributors.
Code licensed under an Apache-2.0 License. Documentation licensed under CC BY 4.0.
https://rxjs.dev/api/operators/filter