2

I am trying to get distinct values of a property in an observable array.

  let pt$ = Observable.of([{planTypeID : 1, description : 'test 1'}, 
                                {planTypeID : 2, description : 'test 2'}]);
    let planTypeIDs$ = pt$
        .flatMap(a => a)
        .map(a => a.planTypeID).distinct().toArray();

Is this the right way to do it in rxjs, or is there a better way?

1 Answer 1

1
  1. You could use .from instead of .of, that should spare you the .flatMap
  2. distinct will check the reference by default, so if you want to compare for contents you should create some kind of hash or make a custom comparer - but maybe that's not required here.

let pt$ = Observable.from([{planTypeID : 1, description : 'test 1'}, 
                            {planTypeID : 2, description : 'test 2'}]);
let planTypeIDs$ = pt$
    .map(a => a.planTypeID)
    .distinct()
    .toArray();
Sign up to request clarification or add additional context in comments.

2 Comments

I am doing Observable.Of to mimic the code that I have in my project. In the project I am working on, I have a service that uses combinelatest to merge multiple observable array's and return a new array.
Okay - well it's difficult to optimize code that is not visible here ;-) - but then your current solution looks pretty much okay i guess

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.