'How to sort ng-select matched record on top in ng-select angular 5

I am using ng-select autocomplete in my angular application for biding country name and country code. Example - If i enter in search box result will be

India - IN

Indonesia - ID

At a time of loading the i retrieved list of all country code with country name as per knowledge it would be done by using custom search feature of ng-select.

Please check my code given bellow -

<ng-select placeholder="Select Countries" class="custom"
  [items]="countryList | async"
  [multiple]="true"
  bindLabel="countryname"
  [searchFn]="searchcountry"
  (change)="onChange($event)"
  [(ngModel)]="selectedCountry">

  <ng-template ng-label-tmp let-item="item" let-clear="clear">
      <span class="ng-value-label">{{item.countryname}}</span>
      <span class="ng-value-icon right" (click)="clear(item)" aria-hidden="true">×</span>
  </ng-template>

  <ng-template ng-option-tmp let-item="item" let-index="index" let-search="searchTerm">
   <span [ngOptionHighlight]="search">  {{item.countryname}} - {{item.countrycode}} </span>
  </ng-template>

ngOnInit() {
   this.countryList = this.caseService.GetCountryList();
}

searchcountry(term: string, item: any) {
   term = term.toLocaleLowerCase();
   return item.countrycode.toLocaleLowerCase().indexOf(term) > -1 || item.countryname.toLocaleLowerCase().includes(term);
}

Please help me how to reach my final output i am very close now just i want to know how to sort to top the record if country code exact match.

Thanks in advance.



Solution 1:[1]

Below code will convert your you JSON object as plain text and then check for the search term in it. I use this solution mainly as pipe where i pass array of object and search term its work like charm.

searchcountry(term: string, item: any) {
        const REGEXP=/("([a-z]+)":)|\[|\]|\{|\}/g;
        term = term.toLocaleLowerCase();
       return term ? item.filter(itm=>{
        let str=JSON.stringify(itm).tolowerCase();
        str=str.replace(REGEXP,'');
        return str.include(term);
       }): item;
      
    }

Solution 2:[2]

If your country code only consists of two letters (e.g., 'IN' for India), then you could prioritize the country code over the country name as follows:

searchcountry(term: string, item: any) {
   term = term.toLocaleLowerCase();
   return term.length <= 2
      ? item.countrycode.toLowerCase().includes(term)
      : item.countrycode.toLowerCase().includes(term) || item.countryname.toLowerCase().includes(term);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ojesh singh
Solution 2 tilo