[英]JavaScript: Sort mixed array of ASCII string and non-ASCII strings
例如,我有一个数组
let fruits = ["apple", "яблоко", "grape"]
当我做
let result = fruits.sort()
结果将是
["apple", "grape", "яблоко"]
但我希望unicode项目位于结果数组的开头。
您可以检查字符串是否以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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.