Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在JS中,如何对数字和字符串进行排序,同时保持字符串的顺序和前后顺序?_Javascript_Sorting - Fatal编程技术网

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

Javascript 在JS中,如何对数字和字符串进行排序,同时保持字符串的顺序和前后顺序?,javascript,sorting,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(stripC

假设我有这样一个数组:

["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;
};
作为一种变体:

const arr=[“a”,“bb”,1,2,“z”,4,3];
常量排序=[
…arr.filter(el=>typeof el==='string'),
…arr.filter(el=>typeof el==='number').sort(),
];
控制台日志(已排序);

您可以检查类型并将字符串移到顶部

var数组=[“a”,“bb”,1,2,“z”,4,3];
array.sort((a,b)=>
(a的类型==‘数字’)-(b的类型==‘数字’)||
a-b
);

console.log(数组)根据比较函数的返回值,我的建议是:

  • 字符串-编号-->首先是字符串
  • 数字-字符串-->后面的数字
  • 转换为字符串并进行比较
  • var数组=[“a”,“zbb”,1,0,2,“z”,4,3];
    array.sort(函数(a,b){
    返回值(a的类型=='string'&&b的类型=='number')?-1:
    (a的类型=='number'和b的类型=='string')?1:
    a、 toString().localeCompare(b.toString());
    });
    
    console.log(数组)是否还要对字符串进行排序?不,我不需要对实际字符串进行排序。“a”只需要在前面,这不是
    (a的类型=='number')-(b的类型=='number')
    计算为
    布尔-布尔
    ?@Scrimothy
    用数字运算符强制为
    0
    。嗯,是的,这很有趣。CleverWhen是or条件hit?Ohhhh true-true==0,这是错误的nvm。好的,请注意,如果我们需要对字符串进行排序,我们只需要在末尾添加sort。var sorted1=[…arr1.filter(el=>typeof el=='string').sort(),…arr1.filter(el=>typeof el=='number').sort(),];但是这种方法的开销是两个额外分配的数组,并且它不会对数组进行适当的排序)
     ["z", "bb", "a", 1, 2, 3, 4]