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 Observable
and emits the resulting values as an Observable
. map
is used with pipe
which is an instance method of Observable
. Observable
of a string that contains comma separated names.getStdNames(): Observable<string> {
return of("Mahesh, Krishna, Ram");
}
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(","))
);
}
getStdNames() {
this.stdNames$ = this.bookService.getStdNames().pipe(
map(res => res.split(","))
);
}
We can iterate
stdNames$
as following.<ul>
<li *ngFor="let name of stdNames$ | async" >
{{name}}
</li>
</ul>
<li *ngFor="let name of stdNames$ | async" >
{{name}}
</li>
</ul>
It will print
Mahesh
Krishna
Ram
Reference:
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(","))
);
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.
this.filterDemoService.getNumbers().pipe(
tap(n => console.log(n)),
filter(n => n % 2 === 0),
map(n => n + 10),
scan((sum, n) => sum + n)
)
.subscribe(result => console.log(result));
tap(n => console.log(n)),
filter(n => n % 2 === 0),
map(n => n + 10),
scan((sum, n) => sum + n)
)
.subscribe(result => console.log(result));
Reference: