Member-only story
RxJS: Understanding filter
in RxJS
Filtering data is a common operation in programming, and RxJS provides a powerful filter
operator that works on observables. It allows us to remove unwanted values from a data stream based on a condition, similar to JavaScript's Array.filter
.
Example of RxJS
filter
Operator
The filter
operator filters emitted values from an observable based on a condition.
✅ Example: Filtering Even Numbers from a Stream
import { of } from 'rxjs';
import { filter } from 'rxjs/operators';
const numbers$ = of(1, 2, 3, 4, 5, 6);
// Using filter to get only even numbers
numbers$
.pipe(filter(num => num % 2 === 0))
.subscribe(value => console.log(value));
// Output:-
// 2 4 6
Explanation:
numbers$
is an observable that emits values 1, 2, 3, 4, 5, 6.filter(num => num % 2 === 0)
allows only even numbers to pass.- The final observable emits only 2, 4, and 6.
Difference Between RxJS
filter
and JavaScriptfilter
Both RxJS filter
and JavaScript Array.filter
are used to remove unwanted values, but they have key differences.
Example: JavaScript filter
vs RxJS filter
✅ JavaScript filter
(Filtering an Array)
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers);
// Output: [2, 4, 6]