说我有一个像这样的数组:
["a", "bb", 1, 2, "z", 4, 3]
,我希望结果数组是这样:
["a", "bb", "z", 1, 2, 3, 4]
我该怎么写?我将其作为谓词:
export const someBrokenSort = (option1, option2) => {
const numberOption1 = Number(stripCommas(option1));
const numberOption2 = Number(stripCommas(option2));
if (numberOption1 < numberOption2 || isNaN(numberOption1)) return -1;
if (numberOption1 > numberOption2 || isNaN(numberOption2)) return 1;
return 0;
};
但是结果是这样的:
["z", "bb", "a", 1, 2, 3, 4]
答案 0 :(得分:6)
您可以检查类型并将字符串移到顶部。
var array = ["a", "bb", 1, 2, "z", 4, 3];
array.sort((a, b) =>
(typeof a === 'number') - (typeof b === 'number') ||
a - b
);
console.log(array);
答案 1 :(得分:4)
作为一种变体:
const arr = ["a", "bb", 1, 2, "z", 4, 3];
const sorted = [
...arr.filter(el => typeof el === 'string'),
...arr.filter(el => typeof el === 'number').sort(),
];
console.log(sorted);
答案 2 :(得分:0)
根据sort比较函数的返回值,我的建议是:
var array = ["a", "zbb", 1, 0, 2, "z", 4, 3];
array.sort(function (a, b) {
return (typeof a === 'string' && typeof b === 'number') ? -1 :
(typeof a === 'number' && typeof b === 'string') ? 1 :
a.toString().localeCompare(b.toString());
});
console.log(array);