I have a two dropdown selects, one for country and one for nationality. Both dropdowns share an array: countryAndNationalityList.
I'm trying to only display the matching nationality once, as it is the same for each country.
<select class="form-control" formControlName="residence_country">
<option *ngFor="let item of removeNationalityDuplicates(countryAndNationalityList.sort(sortCountryAsc))" [ngValue]="item.country">{{item.country}}</option>
</select>
<select class="form-control" formControlName="nationality">
<option value="" disabled>Your Nationality?</option>
<option *ngFor="let item of countryAndNationalityList.sort(sortNationalityAsc)" [ngValue]="item.nationality">{{item.nationality}}</option>
</select>
My countryAndNationalityList array looks like this:
[{country: "United Arab Emirates Abu Dhabi", nationality: "Emirati"},
{country: "United Arab Emirates Ajman", nationality: "Emirati"},
{country: "United Arab Emirates Al-Quwain", nationality: "Emirati"},
{country: "United Arab Emirates Dubai", nationality: "Emirati"},
{country: "United Arab Emirates Fujairah", nationality: "Emirati"},
{country: "United Arab Emirates Ras Al Khaimah", nationality: "Emirati"},
{country: "United Arab Emirates Sharjah", nationality: "Emirati"}]
I am trying to remove the duplicate Emirati in the Nationality dropdown using a function: removeNationalityDuplicates that remove duplicates like this:
<select class="form-control" formControlName="nationality">
<option value="" disabled>Your Nationality?</option>
<option *ngFor="let item of removeNationalityDuplicates(countryAndNationalityList.sort(sortNationalityAsc))" [ngValue]="item.nationality">{{item.nationality}}</option>
</select>
where removeNationalityDuplicates is
removeNationalityDuplicates(array) {
return [... new Set(array)];
}
sortNationalityAsc(previous, next) {
return previous.nationality > next.nationality;
}
I have also tried using:
removeNationalityDuplicates(array) {
return array.reduce((uniqueArr, curVal)=> {
if (!uniqueArr.includes(curVal.nationality)) {
uniqueArr.push(curVal);
}
return uniqueArr;
}, []);
}
How do remove the duplicate nationalities?
removeNationalityDuplicates(array) {
return Array.from(new Set(array.map(x => x.nationality)));
}
Explanation:
array.map(x => x.nationality)
create a new array with only the nationality
keynew Set(array.map(x => x.nationality))
create a set of this array ( works like distinct )Array.from(new Set(array.map(x => x.nationality)));
convert the set to an array.