erevos13
erevos13

Reputation: 411

How to filter an array with RxJS operator

Hello to every one i am new to RxJs and reactive programming i would like to filter an array like this:

let subscription = Rx.Observable.from([{id: 1}, {id: 2}, {id: 3}],[{id: 4}, {id: 5}, {id: 6}]);

if i have one array a i can do this:

let subscription = Rx.Observable.from([{id: 1}, {id: 2}, {id: 3}]);


subscription.filter(x => x.id === 1).subscribe(x => console.log(x));

But how i can to do with the second array?

Upvotes: 3

Views: 4369

Answers (2)

martin
martin

Reputation: 96891

If you know you'll always have array of arrays you can flatten the array and then run filter:

const o = Rx.Observable.of([{id: 1}, {id: 2}, {id: 3}],[{id: 1}, {id: 2}, {id: 3}])
  .concatMap(array => array) // flatten the array into single emissions
  .filter(x => x.id === 1)
  .subscribe(x => console.log(x));

I'm using .of that accepts multiple arguments. However it takes them as they are unlike the from method that iterates the array.

Upvotes: 4

Axnyff
Axnyff

Reputation: 9944

There are a couple of solutions. The easy way is just to create the right observable.

  • You could directly create the right observable by concatenating the array in your input of from:

    let subscription = Rx.Observable.from([{id: 1}, {id: 3}].concat([{id: 1}]));
    
  • You could use Rx.Observable.of which directly takes as many arguments as value in the created Observable and use the spread operator:

    let subscription = Rx.Observable.of(...[{id: 1}, {id: 3}].concat(...[{id: 1}]));
    
  • You could also merge two different observables:

    let subscription = Rx.Observable.from([{id: 1}
                          .merge(Rx.Observable.from([{ id: 1}]);
    

There are possibly other solutions that could work like using an array of array and then flatMapping the array.

Upvotes: 0

Related Questions