为什么localeCompare不能按我预期的那样工作?

时间:2018-07-30 17:05:54

标签: javascript sorting

我尝试按字母顺序对数组数据进行排序,但我认为有些问题。

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 ...

任何建议,我应该如何使用localecompare函数。

2 个答案:

答案 0 :(得分:2)

这是因为aá具有相同的base lettera

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的建议编写自定义排序算法。

答案 1 :(得分:1)

如果无法使用Search-Mailbox -Identity s@test.at -searchquery {received<=9/1/2018 AND subject:test} -DeleteContent 来完成此操作,则好像您必须编写自己的分类器:

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