Back to course

Common Operators: map and filter

The Complete Angular Developer: From Zero to Hero

54. Common Operators: map and filter

Operators are pure functions that take an Observable as input and return a new Observable. They are chained using the pipe() method.

1. The pipe() Function

pipe() is used to sequence multiple operators, applying transformation or filtering logic one after another.

typescript import { of } from 'rxjs'; import { map, filter } from 'rxjs/operators';

of(1, 2, 3, 4, 5).pipe( // operator 1 // operator 2 // ... ).subscribe(...);

2. map Operator (Transformation)

map is equivalent to the JavaScript array map method. It applies a function to each value emitted by the source Observable and emits the result.

Example: Doubling Numbers

typescript of(1, 2, 3).pipe( map(value => value * 2) // Transforms 1 -> 2, 2 -> 4, 3 -> 6 ).subscribe(result => console.log('Mapped:', result)); // Output: 2, 4, 6

// Practical use: transforming API response structure: this.http.get<User[]>(...).pipe( map(users => users.map(user => user.name)) // Extract only names );

3. filter Operator (Selection)

filter determines which values pass through the Observable stream based on a predicate function (a function returning a boolean).

Example: Filtering Even Numbers

typescript of(1, 2, 3, 4, 5).pipe( filter(value => value % 2 === 0) // Only keeps 2 and 4 ).subscribe(result => console.log('Filtered:', result)); // Output: 2, 4

// Combined Example: const clicks$ = fromEvent(document, 'click'); clicks$.pipe( filter((event: MouseEvent) => event.clientY > 100), // Only clicks below the 100px mark map(event => event.clientX) ).subscribe(x => console.log('X position:', x));