我提出了一种对包含混合值(数字、字符串、null、未定义的值)的数组进行升序排序的方案。
const arr = [null, 'b46', '+', 'Яромир Ягр', '76region', 2, 9999999, 'Эркер', '', 0, 3, 33, 765, '366', '77rus', 'ааэ', null, null, '200', undefined, 'ААА', '1', '40', 88, 'cat', undefined, 'apple', 4, '55555', 777, 12, 6, 0, '55', 8, null, undefined, ' Жу', 'жа', 'bbbb', ' Xz', ' Z', 'aa', undefined];
const sortAsc = (arr) => {
const undefinedAndNulls = arr.filter(val => val === null || val === undefined);
const numbers = arr.filter(val => !isNaN(val) && val !== null);
const sortedNumbers = numbers.sort((a, b) => a - b);
const rest = arr.filter(val => val && isNaN(val));
const sortedRest = rest.sort((a, b) => {
const val1 = a || '';
const val2 = b || '';
const valueA = val1.toString().trimLeft();
const valueB = val2.toString().trimLeft();
return valueA.localeCompare(valueB);
});
return [...undefinedAndNulls, ...sortedNumbers, ...sortedRest];
};
结果:
[null, null, null, undefined, undefined, null, undefined, undefined, '', 0, 0, '1', 2, 3, 4, 6, 8, 12, 33, '40', '55', 88, '200', '366', 765, 777, '55555', 9999999, '+', '76region', '77rus', 'aa', 'apple', 'b46', 'bbbb', 'cat', ' Xz', ' Z', 'ААА', 'ааэ', 'жа', ' Жу', 'Эркер', 'Яромир Ягр'];