BACK
Lessons15. filter: let through only what you need
Lessons · 15

15. filter: let through only what you need

filter — let through by a condition

filter(predicate) works like a turnstile. Each value "asks" the predicate function, "do I get through?" If true, the value moves on. If false, it's dropped as if it never existed.

of(1, 2, 3, 4).pipe(filter(x => x % 2 === 0))
// 1 ✗ → 2 ✓ → 3 ✗ → 4 ✓
// The subscriber sees: 2, 4

Order in pipe matters

Operators inside pipe apply top to bottom. Put filter before map and the unwanted values are weeded out earlier, so map never wastes time on them.

Glossary

  • Predicate — a function that returns true or false. Used to decide "let through or not."

Your task

  1. Inside pipe, first add filter(value => value % 2 === 0) — that keeps only the even numbers.
  2. The comma after the first operator is required!
  3. Then add map(value => value * 10).
  4. Expected output: 20 → 40 → 60 (the evens in 1..6 are 2, 4, 6; each multiplied by 10).
Solution spoiler · click to reveal
const { of, filter, map } = Rx;

const source$ = of(1, 2, 3, 4, 5, 6);

const result$ = source$.pipe(
  filter(value => value % 2 === 0),
  map(value => value * 10)
);

result$.subscribe(value => console.log(value));
script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...