As I am building the e-commerce app for the other startup, I ran into a problem where I had to filter an array of objects in an Observable. The problem was not hard and the solution is quite simple and I will share that in this post.

RxJS operators

I think before going into this, it’s important to understand some of the RxJS operators, mainly the pipe operator.

Pipe

You can have a read of it’s definition on the RxJS website but in summary it provides a cleaner way of chaining together multiple functions

Map

If you have used the map method of the array type in Javascript, then you know what this does. It applies every your defined function to every value emitted by the Observable.

Filter

This one’s also self-explanatory. I mean, you supply a function to it that returns a boolean which checks whether the value passes the conditions specified by the Observable.

Solution

Now, let’s look at the solution for it. Firstly,

This is what the itemObservable looks like

private items: Observable<Item[]>;
this.itemObservable.pipe (
   map(items => 
    items.filter(item => item.name.toLowerCase().indexOf(query) > -1)) )

Yeap, it’s really that simple. Pipe the item array in the itemObservable, map each item in the array and check whether or not it matches the condition. The condition in our case is to check whether or not it matches the search query.

Like the blog? Subscribe for updates

As usual, if you find any of my posts useful support me by  buying or even trying one of my apps on the App Store. 

https://mydaytodo.com/apps/

Also, if you can leave a review on the App Store or Google Play Store, that would help too.


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *