Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort special letters (typescript)?

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());
            });
like image 606
Alex Avatar asked Sep 07 '25 02:09

Alex


1 Answers

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')));
like image 160
georg Avatar answered Sep 10 '25 01:09

georg