对包含数字和字符串的数组进行排序

Kom*_*sal 18 javascript arrays string numbers ecmascript-6

我试图将包含字符串,数字和数字的数组排序为字符串(例如'1','2').我想对这个数组进行排序,以便排序的数组首先包含数字,然后是包含数字的字符串,最后是字符串.

var arr = [9,5,'2','ab','3',-1 ] // to be sorted
arr.sort()
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
//arr = [-1, "2", 5, 9, "ab"] // actual result
Run Code Online (Sandbox Code Playgroud)

我也试过了

var number =[];
var char =[];
arr.forEach(a=>{
 if(typeof a == 'number') number.push(a);
 else char.push(a);
})
arr = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
//  arr = [-1, 5, 9, "2", "ab", "3"]// actual result
Run Code Online (Sandbox Code Playgroud)

Jon*_*lms 20

最短的可能是:

 arr.sort((a, b) => ((typeof b === "number") - (typeof a === "number")) || (a > b ? 1 : -1));
Run Code Online (Sandbox Code Playgroud)


Nic*_*ons 10

您可以先将整数排序,然后使用非整数排序.filter()来分隔两种数据类型.

请参阅下面的工作示例(阅读代码注释以获得解释):

const arr = [9,5,'2','ab','3',-1];

const nums = arr.filter(n => typeof n == "number").sort(); // If the data type of a given element is a number store it in this array (and then sort)
const non_nums = arr.filter(x => typeof x != "number").sort(); // Store everything that is not a number in an array (and then sort)

const res = [...nums, ...non_nums]; // combine the two arrays
console.log(res); // [-1, 5, 9, "2", "3", "ab"]
Run Code Online (Sandbox Code Playgroud)

  • 相反,性能更好.这称为[_divide and conquer_](https://www.ics.uci.edu/~eppstein/161/960118.html).由于排序通常是O(n.log(n)),因此制作2种基数n比制作一种基数2n更好.无论如何,争论排序一些项目的性能是没有意义的. (6认同)
  • 这里的表现不好.Jonas的解决方案包含了一个单一的解决方案. (2认同)
  • @Jony-Y不同意.如果`nums.includes(x)`将替换为`typeof x ==="string"`它会明显更快(但需要更多内存)[理论上,JS中的性能总是一个非确定性的东西] (2认同)

ksa*_*sav 4

看来您在第二次尝试中已经完成了大部分工作。我在这里所做的一切都是用于将和Array.concat的排序结果连接在一起。numberchar

var arr = [9, 5, '2', 'ab', '3', -1] // to be sorted
var number = [];
var char = [];
arr.forEach(a => {
  if (typeof a == 'number') number.push(a);
  else char.push(a);
})


var sorted = number.sort().concat(char.sort());
console.log(sorted)
Run Code Online (Sandbox Code Playgroud)

  • @komal `a>b` 返回 `true` 或 `false`,而需要一个数字 (3认同)