3

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?

2
  • Do you want to emit all the {id : n} object from your two arrays? Commented Jan 7, 2018 at 11:01
  • yes i like to search from both array the {id: n}. Commented Jan 7, 2018 at 11:04

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

yes that very nice. But what about in case where i receive from an API and is an already mult array. ?
It's an array of arrays? If so, the flatMapping should work. subscription.flatMap(x => Rx.Observable.from(x))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.