Learn RxJS
Search…
filter

signature: filter(select: Function, thisArg: any): Observable

Emit values that pass the provided condition.

πŸ’‘ If you would like to complete an observable when a condition fails, check out takeWhile!
​​
​
​

Examples

Example 1: filter for even numbers
1
// RxJS v6+
2
import { from } from 'rxjs';
3
import { filter } from 'rxjs/operators';
4
​
5
//emit (1,2,3,4,5)
6
const source = from([1, 2, 3, 4, 5]);
7
//filter out non-even numbers
8
const example = source.pipe(filter(num => num % 2 === 0));
9
//output: "Even number: 2", "Even number: 4"
10
const subscribe = example.subscribe(val => console.log(`Even number: ${val}`));
Copied!
Example 2: filter objects based on property
1
// RxJS v6+
2
import { from } from 'rxjs';
3
import { filter } from 'rxjs/operators';
4
​
5
//emit ({name: 'Joe', age: 31}, {name: 'Bob', age:25})
6
const source = from([
7
{ name: 'Joe', age: 31 },
8
{ name: 'Bob', age: 25 }
9
]);
10
//filter out people with age under 30
11
const example = source.pipe(filter(person => person.age >= 30));
12
//output: "Over 30: Joe"
13
const subscribe = example.subscribe(val => console.log(`Over 30: ${val.name}`));
Copied!
Example 3: filter for number greater than specified value
1
// RxJS v6+
2
import { interval } from 'rxjs';
3
import { filter } from 'rxjs/operators';
4
​
5
//emit every second
6
const source = interval(1000);
7
//filter out all values until interval is greater than 5
8
const example = source.pipe(filter(num => num > 5));
9
/*
10
"Number greater than 5: 6"
11
"Number greater than 5: 7"
12
"Number greater than 5: 8"
13
"Number greater than 5: 9"
14
*/
15
const subscribe = example.subscribe(val =>
16
console.log(`Number greater than 5: ${val}`)
17
);
Copied!

Additional Resources

Last modified 9mo ago