I'm trying to sort a Sector
array and a Province
array based on the language.
sector.ts
:
export interface Sector {
id: string;
Label_FR: string;
Label_NL: string;
}
province.ts
:
export interface Province {
id: string;
frenchName: string;
dutchName: string;
}
constructor(
private readonly _translateService: TranslateService,
private statisticsManager: StatisticsManager) {
let currentLang = _translateService.currentLang; // 'fr' / 'nl'
statisticsManager.sectors$.pipe(takeUntil(this.onDestroy$))
.subscribe((sector: Sector[]) => (this.sectorOptions = sector));
statisticsManager.provinces$.pipe(takeUntil(this.onDestroy$))
.subscribe((province: Province[]) => (this.provinceOptions = province));
this._translateService.onLangChange.subscribe(() => {
this.sortFilters();
})
}
sortFilters() {
let currentLang = this._translateService.currentLang;
this.sectorOptions = this.sectorOptions.sort((a, b) => {
if (currentLang == 'fr') {
return this.sortFunc(a.Label_FR, b.Label_FR);
} else {
return this.sortFunc(a.Label_NL, b.Label_NL);
}
});
this.provinceOptions = this.provinceOptions.sort((a, b) => {
if (currentLang == 'fr') {
return this.sortFunc(a.frenchName, b.frenchName);
} else {
return this.sortFunc(a.dutchName, b.dutchName);
}
});
}
sortFunc(obj1: any, obj2: any) {
if (obj1 > obj2) {
return 1;
} else if (obj1 < obj2) {
return -1;
} else {
return 0;
}
}
The code does the job but is really 'long' for that kind of task, is there any short / optimisation to achieve the same result?
localeCompare
forsortFunc
implementation? \$\endgroup\$