user2999287 user2999287 - 1 month ago 12
Javascript Question

Rx js filter method does not return the filter array

I want to return filtered observable from Array, but when I am subscribing to this observable it does not return the filtered array, it returns the original array. why?

const filterBy = {title: 'javascript'};
const items = [{title: 'javascript'}, {title: 'css'}, {title: 'html'}];


const filtered = Rx.Observable.of(items).filter(i => {
const filtered = i.filter(item => item.title.indexOf(filterBy.title) !== -1);
console.log('filtered', filtered); // The array length is one
return filtered;
})

filtered.subscribe(f => console.log(f) // The array length is three);

Answer

Because this is not how you're supposed to use Observables in RxJS. Filters in RxJS always return another Observables and never directly values the processed.

Operator filter() expects you to return boolean true or false based on whether you want to to include or exclude the item from the processed Observable stream. Since you're passing the entire array as a single value with Rx.Observable.of(items) it always passes everything or nothing (the returned array is converted into boolean).

So let's use Observable.from static method to create an Observable from an iterable that'll emit each item in the array as a single value and then just filter() to exclude all items that don't match the predicate.

const filterBy = {title: 'javascript'};
const items = [{title: 'javascript'}, {title: 'css'}, {title: 'html'}];

const observable = Rx.Observable.from(items).filter(item => {
    return item.title.indexOf(filterBy.title) !== -1;
});

observable.subscribe(f => console.log(f));