Member-only story

RxJS: Understanding filter in RxJS

Abhishek Wadalkar
2 min read3 days ago

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 JavaScript filter

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]

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Abhishek Wadalkar
Abhishek Wadalkar

Written by Abhishek Wadalkar

Passionate Frontend developer with 4 years experience, crafting seamless, user-centric web experiences. Exploring the world of web development and constantly.

No responses yet

Write a response