数组中的奇偶排序 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/7 3:56:17

我们需要编写一个 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
]

相关文章


有用资源