JavaScript:对ASCII字符串和非ASCII字符串的混合数组进行排序

时间:2018-05-15 05:13:52

标签: javascript

例如我有一个数组

let fruits = ["apple", "яблоко", "grape"]

当我这样做时

let result = fruits.sort()

结果将是

["apple", "grape", "яблоко"]

但我希望unicode项目位于结果数组的开头。

1 个答案:

答案 0 :(得分:3)

您可以检查字符串是否以sort函数中的单词字符开头:

const fruits = ["apple", "яблоко", "grape"];
const isAlphabetical = str => /^\w/.test(str);
fruits.sort((a, b) => (
  isAlphabetical(a) - isAlphabetical(b)
    || a.localeCompare(b)
))
console.log(fruits);

更强大的排序功能会检查每个角色与其他角色的对比:

const fruits = ["apple", "яблоко", "grape", 'dog', 'foo', 'bar', 'локоfoo', 'fooлоко', 'foobar'];
const isAlphabetical = str => /^\w/.test(str);
const codePointValue = char => {
  const codePoint = char.codePointAt(0);
  return codePoint < 128 ? codePoint + 100000 : codePoint;
};
fruits.sort((a, b) => {
  for (let i = 0; i < a.length; i++) {
    if (i >= b.length) return false;
    const compare = codePointValue(a[i]) - codePointValue(b[i]);
    if (compare !== 0) return compare;
  }
  return true;
})
console.log(fruits);