如何使用JavaScript从数组中分离字母和数字
我们有一个数组,其中包含一些数字文字和一些混合的字符串文字,并且我们需要编写一个将两种类型分开的排序函数,并且两种类型也应在其中进行排序。
该排序功能的代码将为-
示例
const arr = [1, 5, 'fd', 6, 'as', 'a', 'cx', 43, 's', 51, 7];
const sorter = (a, b) => {
const first = typeof a === 'number';
const second = typeof b === 'number';
if(first && second){
return a - b;
}else if(first && !second){
return -1;
}else if(!first && second){
return 1;
}else{
return a > b ? 1 : -1;
}
};
arr.sort(sorter);
console.log(arr);输出结果
控制台中的输出将为-
[ 1, 5, 6, 7, 43, 51, 'a', 'as', 'cx', 'fd', 's' ]
热门推荐
5 短祝福语简短暖心
10 结婚祝福语粤语大全简短
11 晚上祝福语女生文案简短
12 法语妈妈生日祝福语简短
13 药厂开工祝福语大全简短
14 蛋糕节日祝福语简短英文
15 跨年的生日祝福语简短
16 文案祝福语英文短句简短
17 在家聚餐婚礼祝福语简短
18 学生节祝福语大全简短