Home > Net >  Remove duplicate values from api
Remove duplicate values from api

Time:12-02

I'm displaying values from the API in a dropdown menu. But there are some duplicate values that I want to remove.

[0: {CountryCode: "US", Prof ID: 31, Scope: "National"} 
1: {CountryCode: "US" , Prof ID: 31, Scope: "Self"}
2: {CountryCode: "US", Prof ID: 31, Scope: "Specialty"}
3: {CountryCode: "IT", Prof ID: 31, Scope: "Carting"}]

**HTMLcode:

              <div >
                <label for="country"  required>Country:</label><br>
                <select  required=""  [(ngModel)]="detailM" formControlName="PropertyCountryCode"> 
                    <option [ngValue]="null"></option>    
                    <option  *ngFor="let details of detail" >{{details.CountryCode}}
                  </option>
                </select>     
                <button (click)="filterCountry()">button</button>  
             </div>
`

``

ts code

` ngOnInit(){   

    this.dataService.getUserDetail().subscribe(details=>{(this.detail=details)});
 }`


Result This is my output ----------------------------------- Expected Output]

CodePudding user response:

you can use set to remove duplicate items.

first define a new property for your component:

  countryCodes: string[] = [];

then populate it with:

ngOnInit(){

this.dataService.getUserDetail().subscribe(details => { (this.countryCodes = this.getCountryCodes(details))});

}

and dd this method to the component:

 getCountryCodes(items: { CountryCode: string, "Prof_ID": number, Scope: string }[]) {
    const set = new Set<string>();
    items.forEach(item => (set.add(item.CountryCode)));
    return Array.from(set);
  }

and change your html:

<option *ngFor="let item of countryCodes">{{item}}
  • Related