本文介绍了如何对特殊字母(打字稿)进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在ts中排序一些字母... sort方法和localCompare()以Ä,Å,Ö(而不是Å,Ä,Ö)的方式进行排序.如何准确地对任何字母进行排序?

I want to sort some letters in ts... sort method and localCompare() sort in this way Ä, Å, Ö, instead of Å, Ä, Ö. How to sort any letters corectly?

我有一个对象列表:

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

更新

是的,georg的回答是正确的:我也发现了这一点:

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

相同的结果.

非常感谢!

非常重要

不要使用localCompare,因为它在执行时会变得更糟.

Don't use localCompare because it's very worse at execution time.

使用Intl.Collat​​or!

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显然取决于语言环境,并且不同的语言环境使用不同的规则(归类")比较扩展字符.例如,用英语,具有不同音素符号的A都是一样的,而瑞典语则将它们区别对待:

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

这篇关于如何对特殊字母(打字稿)进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 18:22