How to sort special letters (typescript)?

▼魔方 西西 提交于 2019-12-13 14:22:28

问题


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());
            });

回答1:


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')));


来源:https://stackoverflow.com/questions/48583099/how-to-sort-special-letters-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!