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)
看来您在第二次尝试中已经完成了大部分工作。我在这里所做的一切都是用于将和Array.concat
的排序结果连接在一起。number
char
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)
归档时间: |
|
查看次数: |
2580 次 |
最近记录: |