Reputation: 13
Have a stream, wherein the object contains and array of string. I have a filter which is another array of string. The filter should only emit those items where the intersection of the array is not empty.
This is the psuedo code of what I want to do.
genreFilter: string["poetry", "fiction"]
this.books$ = this.bookInventoryService.getBooks()
.filter(book => {
for( let genre of genreFilter) {
if (book.genres.contains(genre) {
return true;
}
}
});
Is there a way to do array intersection?
Upvotes: 1
Views: 7065
Reputation: 18663
Not really an Rx question, but if you are compiling to ES6 you can create a Set
from the filter and then use the Array#some to determine if there are any intersections.
const genreFilter: Set<string> = new Set(["poetry", "fiction"]);
this.books$ = this.bookInventoryService.getBooks()
.filter(book => book.genres.some(genre => genreFilter.has(genre)));
If Set
is not available you can still do it with an Array
if the comparison set is small. Or if the set is large you could create an object out of the filter so you get O(1) lookup:
const genreFilter = ["poetry", "fiction"]
.reduce((obj, key) => {
obj[key] = true
return obj;
}, {});
this.books$ = this.bookInventoryService.getBooks()
.filter(book => book.genres.some(genre => genreFilter[genre]));
Upvotes: 1