 ## Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

# Filter Events Based on a Predicate with RxJS filter RxJS
^5.0.0

through a predicate function that tells what is the criteria to pass or reject an event. This lesson introduces filter: an operator that allows us to let only certain events pass, while ignoring others. ### Code ### You must be a Member to view code

Access all courses and lessons, track your progress, gain confidence and expertise.

Become a Member
and unlock code for this lesson ### Discuss ### Transcript

The next operator we're going to see is Filter. Suppose we have an observable of numbers, like zero, one, two, three, etc., which is generated by that interval function above, and we would like to have only even numbers. We want to ignore out the odd numbers like one, three, five, seven, etc.

We do that with Filter. It allows us to remove some of events by giving a function which is called a predicate. Predicate functions are simply they take an argument and they should return true or false. That's what a predicate function means.

We return true when this X, which is the input event on this input observables, should pass. If it passes, it will appear here on the bottom. We return false when it should be ignored. In case of odd and even numbers, if the modulo of X with two is zero, then that's an even number, and this comparison would be true. That's why even numbers would pass.

But if this modulo two with X would be one, then that means that we have an odd number, and that's why this comparison would be false, and the event would not pass. One does not pass, for instance. It would return false.

Two would pass so the predicate would return true, and then etc., and we get an observable output at the bottom here with only even numbers. Let's call that in actual JavaScript. We take the modulo with two, check if it's zero, and then this is now observable bar.

If we run this, we see that bar has only even numbers. Foo is ticking every second, but every other second it gives an odd number which we ignore. To recap, Filter allows you to pick certain events, and ignore others, through a predicate function that tells what is the criteria to pass or reject an event.