filter
signature: filter(select: Function, thisArg: any): Observable
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!
Why use filter
?
filter
?This operator is your go-to when you need to sift out unwanted values from an observable stream. Think of it as a fisherman's net, catching only the types of fish you desire while allowing others to slip through.
The critical point to remember is that filter
will only emit values that meet the specified condition. If no values in the observable satisfy the condition, nothing gets emitted. It's a strict bouncer at a club's entrance, only letting in those who fit the criteria.
Also, for scenarios where you not only want to filter values but also transform them, map
is an ideal companion to filter
. Use them in tandem to both shape and refine your data streams.
Examples
Example 1: filter for even numbers
( StackBlitz | jsBin | jsFiddle )
Example 2: filter objects based on property
( StackBlitz | jsBin | jsFiddle )
Example 3: filter for number greater than specified value
( StackBlitz | jsBin | jsFiddle )
Related Recipes
Additional Resources
filter 📰 - Official docs
filter - In Depth Dev Reference
Adding conditional logic with filter 🎥 💵 - John Linquist
Filtering operator: filter 🎥 💵 - André Staltz
Build your own filter operator 🎥 - Kwinten Pisman
📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/filter.ts
Last updated