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

3
例如,我有一个数组。
let fruits = ["apple", "яблоко", "grape"]

当我执行时

let result = fruits.sort()

结果将是

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

但我希望Unicode项目在结果数组的开头。


https://dev59.com/9HA65IYBdhLWcg3wyh17#23618442 - deEr.
3
它们都是Unicode字符串。 - melpomene
@melpomene 如果您认为这个问题的措辞不正确,您可以更改问题标题。 - rendom
这是错误的想法。我不明白你试图实现什么。 - melpomene
1
这仍然不是关于措辞的问题。 - melpomene
显示剩余3条评论
1个回答

3
您可以在排序函数中检查字符串是否以单词字符开头:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接