I want to sort some letters in ts... sort method and localCompare() sort in this way Ä, Å, Ö, instead of Å, Ä, Ö. How to sort any letters corectly?
I have a list of objects:
class MyObj { id:number,
name: string,
type:number
}
I tried var list: MyObj[] = a list of objects
list.sort(function (a, b) {
return a.name.toUpperCase().localeCompare(b.name.toUpperCase());
});
UPDATE
Yes, georg answer was correct: I found this too:
var strings = ["Ålex", "Ålex3", "Älex2"];
var sorter = new Intl.Collator("sv", { usage: "sort" });
strings.sort(sorter.compare);
same result.
Thanks a lot!
VERY IMPORTANT
Don't use localCompare because it's very worse at execution time.
Use Intl.Collator!
var browserLanguage = function () {
const defaultLanguage = "en";
const browserLanguage = this.window.navigator.language ||
(this.window as any).navigator.browserLanguage;
const currentLanguage = browserLanguage.split('-')[0];
if (supportedLanguages.indexOf(currentLanguage) < 0) {
return defaultLanguage;
} else {
return currentLanguage;
}
}
const intlCollator = new Intl.Collator(browserLanguage, { usage: "sort" });
list.sort(function (a, b) {
return intlCollator.compare(a.toUpperCase(), b.toUpperCase());
});
localeCompare obviously depends on the locale, and different locales use different rules ("collations") to compare extended characters. For example, in English, As with different diacritics are all the same, while Swedish treats them differently:
console.log(["Älex2", "Ålex0", "Ålex3", "Alex1"].sort(( a, b ) => a.localeCompare(b, 'en')));
console.log(["Älex2", "Ålex0", "Ålex3", "Alex1"].sort(( a, b ) => a.localeCompare(b, 'sv')));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With