Sorting odd and even elements separately JavaScript



We are required to write a JavaScript function that takes in an array of Integers.

The function should sort the array such all the odd numbers come first, then followed by the even number.

The order of odd or even numbers within themselves is not of much importance, but all odd numbers should come before any even number.

For example −

If the input array is −

const arr = [0, 2, 4, 6, 8, 0, 1, 3, 5, 7, 9, 1];

Then the sorted array should be (it’s one of the many solutions where all odds are before evens) −

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

Example

const arr = [0, 2, 4, 6, 8, 0, 1, 3, 5, 7, 9, 1];
const sortOddEven = (arr = []) => {
   let i = 0, j, temp;
   while (i < arr.length - 1) {
      j = i;
      while (!(arr[j] % 2) && arr[j + 1] % 2) {
         temp = arr[j];
         arr[j] = arr[j + 1];
         arr[j + 1] = temp;
         if (!j) {
            break;
         };
         j--;
      };
      i++;
   };
};
sortOddEven(arr);
console.log(arr);

Output

And the output in the console will be −

[
   1, 3, 5, 7, 9,
   1, 0, 2, 4, 6,
   8, 0
]

Advertisements