filter

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

Emit values that pass the provided condition.


:bulb: If you would like to complete an observable when a condition fails, check
out takeWhile!


Examples

Example 1: filter for even numbers

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { filter } from 'rxjs/operators';
  3. //emit (1,2,3,4,5)
  4. const source = from([1, 2, 3, 4, 5]);
  5. //filter out non-even numbers
  6. const example = source.pipe(filter(num => num % 2 === 0));
  7. //output: "Even number: 2", "Even number: 4"
  8. const subscribe = example.subscribe(val => console.log(`Even number: ${val}`));
Example 2: filter objects based on property

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { filter } from 'rxjs/operators';
  3. //emit ({name: 'Joe', age: 31}, {name: 'Bob', age:25})
  4. const source = from([{ name: 'Joe', age: 31 }, { name: 'Bob', age: 25 }]);
  5. //filter out people with age under 30
  6. const example = source.pipe(filter(person => person.age >= 30));
  7. //output: "Over 30: Joe"
  8. const subscribe = example.subscribe(val => console.log(`Over 30: ${val.name}`));
Example 3: filter for number greater than specified value

( jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/interval';
  2. import { filter } from 'rxjs/operators';
  3. //emit every second
  4. const source = interval(1000);
  5. //filter out all values until interval is greater than 5
  6. const example = source.pipe(filter(num => num > 5));
  7. /*
  8. "Number greater than 5: 6"
  9. "Number greater than 5: 7"
  10. "Number greater than 5: 8"
  11. "Number greater than 5: 9"
  12. */
  13. const subscribe = example.subscribe(val =>
  14. console.log(`Number greater than 5: ${val}`)
  15. );

Additional Resources


:file_folder: Source Code:
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/filter.ts