简体   繁体   English

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

[英]JavaScript: Sort mixed array of ASCII string and non-ASCII strings

For example I have an array 例如,我有一个数组

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

When I do 当我做

let result = fruits.sort()

Result will be 结果将是

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

But I want unicode items to be at the start of result array. 但我希望unicode项目位于结果数组的开头。

You can check to see if the string starts with a word character in the sort function: 您可以检查字符串是否以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); 

A more robust sorting function would check each character against each other character: 更强大的排序功能会检查每个字符与其他字符:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM