需求:數字和英文按 123,abc順序,中文按拼音首字母排序
const ori = ['中', '文', '排', '序', '1中', '1文', '1排', '1序', 'a中', 'a中', 'a排', 'a序', 'c中', 'c文','c排', 'c序', 1, 'a', 'c']
Array 的默認排序方法 sort
sort默認按字符的Unicode編碼進行排序
// 獲取排序前的Unicode編碼
ori.forEach(i => console.log(i.toString().charCodeAt(0)))
// 20013
// 25991
// 25490
// 24207
// 49 * 4
// 97 * 4
// 99 * 4
// 49
// 97
// 99
const sort1 = [...ori]
sort1.sort()
// [1, '1中', '1序', '1排', '1文', 'a', 'a中', 'a中', 'a序', 'a排', 'c', 'c中', 'c序', 'c排', 'c文', '中', '序', '排', '文']
// 查看排序后的Unicode編碼
sort1.forEach(i => console.log(i.toString().charCodeAt(0)))
// 49 * 5
// 97 * 5
// 99 * 5
// 20013
// 24207
// 25490
// 25991
可以看到默認的排序方式,無法完成對中文字符按拼音首字母排序,因此需要借助 localeCompare 方法進行輔助排序
完整的排序方案
export function mixSort(_a, _b) {
const reg = /[a-zA-Z0-9]/
// 比對僅針對字符串,數字參與對比會導致對比的字符串轉為number類型,變成NaN
const a = _a.toString()
const b = _b.toString()
// 比對0號位的原因是字符串中有可能出現中英文混合的情況,這種僅按首位排序即可
if (reg.test(a[0]) || reg.test(b[0])) {
if (a > b) {
return 1
} else if (a < b) {
return -1
} else {
return 0
}
} else {
return a.localeCompare(b)
}
}
const sort2 = [...ori]
sort2.sort((a, b) => mixSort(a, b))
// [1, '1中', '1序', '1排', '1文', 'a', 'a中', 'a中', 'a序', 'a排', 'c', 'c中', 'c序', 'c排', 'c文', '排', '文', '序', '中']
該方法已基本符合預期,如果需要針對首位英文或數字字符相同,后面中文二次排序的情況,就需要額外處理,此處不再展開