How to use .distinct to remove objects from an array via the content of a object property

Viewed 4414

I would like to understand the .distinct operator in my use-case:

I do a search for a country via user input and want to show only one object with a specific content in a property called country.

Explanation:

I have a BehaviorSubject with the content of various objects:

[
 {id:1, country: "United Kingdom", city:"London"},
 {id:2, country: "United Kingdom", city:"Manchester"},
 {id:3, country: "Germany", city:"Berlin"},
 ...
]

The type of the array is for example loc[]:

interface loc {
  id: number;
  country: string;
  city: string;
}

This is the filtering via user input (called 'query' in the code below):

BehaviorSubject
   .map(x => x.filter((l) => 
     l.country.toLowerCase().indexOf(query.toLowerCase()) > -1))

If the user input is 'United' I get a result array with two objects.

To get only one object I used another .map to handle the duplicates (Standard js code to remove duplicates from an array) and return an array with only one object.

  1. How do I remove the duplicates in the array with .distinct?
  2. If you look at the first .map the type of x is loc[]. How do I get the items of the array in the .map operator and not the array type?

Thanks in advance

1 Answers
Related