rxjs

Filter Operator

Filter Operator

In this tutorial, we will learn about the filter operator of RXJS.

Filter Operator:

Filter items emitted by the source Observable by only emitting those that satisfy a specified condition.

Basically, the Filter operator takes items emitted by the source observable and emits only those values that satisfy a specified condition.

Example-1:

import { from } from 'rxjs';
import { filter } from 'rxjs/operators';

const source$ = from([10, 20]).map( x => x +10 ) .filter( x > 20 );

source$.subscribe( data => console.log(data)) 
// output : 30

Example-2:

Now suppose we have an array of object as follows:

dataArr = [
    {
      id: 1,
      name: "Arden",
      gender: "Male",
    },
    {
      id: 2,
      name: "Dyana",
      gender: "Male",
    },
    {
      id: 3,
      name: "Prentice",
      gender: "Male",
    },
    {
      id: 4,
      name: "Chalmers",
      gender: "Female",
    },
    {
      id: 5,
      name: "Cybil",
      gender: "Female",
    },
    {
      id: 6,
      name: "Emelda",
      gender: "Male",
    },
    {
      id: 7,
      name: "Melessa",
      gender: "Female",
    },
    {
      id: 8,
      name: "Nisse",
      gender: "Female",
    },
    {
      id: 9,
      name: "Padgett",
      gender: "Male",
    },
    {
      id: 10,
      name: "Ruthi",
      gender: "Male",
    },
  ];

Now we want to filter only users which have 'male' gender, then let see how we can do that using filter operator:

import { from } from "rxjs";
import { filter, toArray } from "rxjs/operators";
---------------
const source$ = from(this.dataArr);

source$
      .pipe(
        filter((data) => data.gender == "Male"),
        toArray()
      )
      .subscribe((res) => {
        console.log(res);
      });

It will output:

[{id: 1, name: "Arden", gender: "Male"}
{id: 2, name: "Dyana", gender: "Male"}
{id: 3, name: "Prentice", gender: "Male"}
{id: 6, name: "Emelda", gender: "Male"}
{id: 9, name: "Padgett", gender: "Male"}
{id: 10, name: "Ruthi", gender: "Male"}]

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment