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 (Angular). Obvservable as in one of the RxJS operators. 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.

Observable (Angular) & Solution

The scenario is, we have a set of items that we are offering through our e-commerce site for the users to buy. Our app is written in Angular and display items via an item observable. The problem is we need to filter the observable based on a certain query and here’s the solution for it.
private items: Observable<Item[]>;
this.itemObservable.pipe (
   map(items => 
    items.filter(item => item.name.toLowerCase().indexOf(query) > -1)) )
Yes, 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

If you find any of my posts useful and want to support me, you can buy me a coffee 🙂 https://www.buymeacoffee.com/bhumansoni Or you can  buying or even try 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.

2 Comments

Georges · February 26, 2021 at 10:36 am

Very Useful – Thank you

Rahul Kumar · June 13, 2021 at 6:33 pm

good

Leave a Reply

Avatar placeholder

Your email address will not be published.