We are required to write a JavaScript function that takes in an array of numbers and sorts the array such that first all the even numbers appear in ascending order and then all the odd numbers appear in ascending order.
For example: If the input array is −
const arr = [2, 5, 2, 6, 7, 1, 8, 9];
Then the output should be −
const output = [2, 2, 6, 8, 1, 5, 7, 9];
Example
Following is the code −
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);
Output
Following is the output in the console −
[ 2, 2, 6, 8, 1, 5, 7, 9 ]