如何使用 JavaScript 从数组中分离字母和数字

javascriptweb developmentobject oriented programming更新于 2025/9/30 6:36:17

我们有一个数组,其中包含一些数字文字和一些字符串文字,我们需要编写一个排序函数来分离两者,并且两种类型也应该在其中进行排序。

此排序函数的代码将是 −

示例

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'
]

相关文章


有用资源