Why doesn't localeCompare work as I expect?

故事扮演 提交于 2021-01-19 04:28:47

问题


I try to sort array data alphabetically but I think something is not OK.

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"]

The Hungarian alphabet starts with a, á, b, c...

Any suggestion, how should I use localecompare function.


回答1:


In case there is no way to do it with localeCompare it seems as if you have to write your own sorter:

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

Usable as

 array.sort(alphabetically);



回答2:


That's because a and á has the same base letter: a.

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

The difference can be illustrated with the letters a and ä in both swedish and german:

In swedish a and ä don't have the same base letter but are infact two different letters.

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

In german a and ä have the same base letter

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

Your option is to write a custom sorting algorithm as Jonas W suggested.



来源:https://stackoverflow.com/questions/51599040/why-doesnt-localecompare-work-as-i-expect

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