如何使用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' ]
热门推荐
10 感谢韩语老师祝福语简短
11 升职文案高级祝福语简短
12 花童结婚祝福语大全简短
13 向国庆送祝福语简短
14 什么寄语简短祝福语女生
15 客户回礼祝福语大全简短
16 女孩生日祝福语简短创意
17 家长回复节日祝福语简短
18 给外婆敬酒祝福语简短