我正在尝试对包含字符串、数字和数字作为字符串(例如“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
我也尝试过
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
最佳答案
最短的可能是:
arr.sort((a, b) => ((typeof b === "number") - (typeof a === "number")) || (a > b ? 1 : -1));
关于javascript - 对包含数字和字符串的数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53958419/