如何对数字和字符串进行排序,同时保持JS中字符串的顺序和最前面以及后面的数字排序?

时间:2019-01-23 19:22:36

标签: javascript sorting

说我有一个像这样的数组:

["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]

3 个答案:

答案 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比较函数的返回值,我的建议是:

  1. 字符串-数字->字符串优先
  2. 数字-字符串->后面的数字
  3. 转换为字符串并进行比较

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);