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: 2020-10-17T11:29:52+05:30

126 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements