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