为什么区域设置比较没有按我的预期工作?



我尝试按字母顺序对数组数据进行排序,但我认为有些地方不太好。

var items;
// it's OK  
items = ['a', 'á'];
items.sort((a, b) => a.localeCompare(b, 'hu'));
console.log(items); // ["a", "á"]
// it's OK, too
items = ['an', 'án'];
items.sort((a, b) => a.localeCompare(b, 'hu'));
console.log(items); // ["an", "án"]
// hmmm, it's not
items = ['an', 'ál'];
items.sort((a, b) => a.localeCompare(b, 'hu'));
console.log(items); // ["ál", "an"]

匈牙利字母表以a、á、b、c…开头

有什么建议,我应该如何使用localecopare函数。

这是因为aá具有相同的base letter:a
console.log('a'.localeCompare('á', 'hu', { sensitivity: 'base' })); // 0

这种差异可以用瑞典语和德语中的字母aä来说明:

在瑞典语中,aä没有相同的基字母,但实际上是两个不同的字母。

console.log('a'.localeCompare('ä', 'sv', { sensitivity: 'base' })); // -1

在德语中,aä具有相同的基字母

console.log('a'.localeCompare('ä', 'de', { sensitivity: 'base' })); // 0

您的选择是按照Jonas W的建议编写一个自定义排序算法。

如果无法使用localeCompare,则似乎必须编写自己的分类器:

const alphabet = "aábcdefghijklmnopqrstuvwxyz";
function alphabetically(a, b) {
a = a.toLowerCase(), b = b.toLowerCase();
// Find the first position were the strings do not match
let position = 0;
while(a[position] === b[position]) {
// If both are the same don't swap
if(!a[position] && !b[position]) return 0;
// Otherwise the shorter one goes first
if(!a[position]) return 1;
if(!b[position]) return -1;
position++;
}
// Then sort by the characters position
return alphabet.indexOf(a[position]) - alphabet.indexOf(b[position]);
}

可用作

array.sort(alphabetically);

最新更新