如何使用 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'
]

更新於: 20-Aug-2020

964 次檢視

開啟你的職業生涯

透過完成課程獲取認證

開始
廣告
© . All rights reserved.