Angular map vs filter

Asked on May 12, 2019
Hi, What is difference between RxJS map and filter in Angular application?
Provide some examples.

Replied on May 12, 2019

1. RxJS map

map is a RxJS pipeable operator. map applies a given function to each element emitted by the source Observableand emits the resulting values as an Observable. map is used with pipe which is an instance method of Observable
Suppose we have an Observable of a string that contains comma separated names.

getStdNames(): Observable<string> {
   return of("Mahesh, Krishna, Ram");

Now we will map this string into array and return result into Observable of array of names.

stdNames$: Observable<string[]>; 
getStdNames() { 
 this.stdNames$ = this.bookService.getStdNames().pipe(
    map(res => res.split(","))

We can iterate stdNames$ as following.

  <li *ngFor="let name of stdNames$ | async" >

It will print 



2. RxJS filter

RxJS filter is used to filter values emitted by source Observable on the basis of given predicate. If the condition returns true, filter will emit value obtained from source Observable otherwise not. Find the some usability of RxJS filter operator. 

a. Filter value on the basis of given character.

this.stdNames$ = this.filterDemoService.getStdNames().pipe(
  filter(data => data.indexOf(",") > 0),
  map(res => res.split(","))

In the above code, if value emitted by Observable returned by getStdNames() has no (",") character, then it will not pass source Observable to map operator.

b. Filter numbers on the basis of odd/even.

  tap(n => console.log(n)),
  filter(n => n % 2 === 0),
  map(n => n + 10),
  scan((sum, n) => sum + n)
.subscribe(result => console.log(result));


Write Answer

©2023 | Privacy Policy | Contact Us