const arr = ['H80', 'H080', 'H80z', 'apple', '12', '水果', 'title', 'h90'];
sort(arr); // 得到结果: ['12', 'apple', 'h90', 'H080', 'H80', 'H80z', 'title', '水果']
const sort = function(arr: string[]) {
/**
* 分离数字和其他字符
*/
const split = (str: string) => {
return str.split(/(\d+)/).filter(item => !!item);
};
const isNumber = (str: string) => {
return !isNaN(Number(str));
};
arr.sort((a, b) => {
const arrA = split(a);
const arrB = split(b);
for (let i = 0; i < Math.max(arrA.length, arrB.length); i++) {
const strA = arrA[i];
const strB = arrB[i];
// str.localeCompare(undefined)为-1,不符合习惯
if (!strA) {
return -1;
}
if (!strB) {
return 1;
}
// 如果是都是数字字符串,需要先转成Number来比较
if (strA && strB && isNumber(strA) && isNumber(strB)) {
if (Number(strA) > Number(strB)) {
return 1;
} else if (Number(strA) < Number(strB)) {
return -1;
}
}
const compare = strA.localeCompare(strB);
if (compare === 0) {
// 如果相等,进行下一组的比对
continue;
}
return compare;
}
return a.localeCompare(b);
});
return arr;
}