数组中的奇偶排序 - 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 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP