Special type of sort of array of numbers in JavaScript


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];

Output

Then the output should be −

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

Therefore, let’s write the code for this function −

Example

The code for this will be −

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

The output in the console will be −

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

Updated on: 17-Oct-2020

91 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements