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.
I think before going into this, it’s important to understand some of the RxJS operators, mainly the pipe operator.
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
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.
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.
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.
Also, if you can leave a review on the App Store or Google Play Store, that would help too.