陣列中的奇偶排序 - JavaScript


我們需要編寫一個 JavaScript 函式,其中需要輸入一個數字陣列,並給該陣列排序,首先讓所有偶數以升序出現,然後讓所有奇數以升序出現。

例如:如果輸入陣列為 -

const arr = [2, 5, 2, 6, 7, 1, 8, 9];

那麼輸出應該是 -

const output = [2, 2, 6, 8, 1, 5, 7, 9];

範例

以下是程式碼 -

const arr = [2, 5, 2, 6, 7, 1, 8, 9];
const isEven = num => num % 2 === 0;
const sorter = ((a, b) => {
   if(isEven(a) && !isEven(b)){
      return -1;
   };
   if(!isEven(a) && isEven(b)){
      return 1;
   };
   return a - b;
});
const oddEvenSort = arr => {
   arr.sort(sorter);
};
oddEvenSort(arr);
console.log(arr);

輸出

以下是控制檯中的輸出 -

[
   2, 2, 6, 8,
   1, 5, 7, 9
]

更新於: 16-Sep-2020

1K+ 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.