Separate odd and even in JavaScript

In JavaScript, separating odd and even numbers means rearranging an array so that all even numbers appear before all odd numbers. This is commonly achieved using custom sorting functions or array methods like filter().

Using Custom Sort Function

The most efficient approach uses Array.sort() with a custom comparator that prioritizes even numbers:

const arr = [2, 6, 3, 7, 8, 3, 5, 4, 3, 6, 87, 23, 2, 23, 67, 4];
const isEven = num => num % 2 === 0;

const sorter = (a, b) => {
    if(isEven(a) && !isEven(b)){
        return -1;  // a (even) comes before b (odd)
    }
    if(!isEven(a) && isEven(b)){
        return 1;   // b (even) comes before a (odd)
    }
    return 0;       // both same type, maintain order
};

arr.sort(sorter);
console.log(arr);
[
  2, 6, 8, 4, 6, 2,
  4, 3, 7, 3, 5, 3,
  87, 23, 23, 67
]

Using Filter Method

An alternative approach uses filter() to separate arrays and then combines them:

const numbers = [2, 6, 3, 7, 8, 3, 5, 4, 3, 6, 87, 23, 2, 23, 67, 4];

const evenNumbers = numbers.filter(num => num % 2 === 0);
const oddNumbers = numbers.filter(num => num % 2 !== 0);
const separated = [...evenNumbers, ...oddNumbers];

console.log("Even numbers:", evenNumbers);
console.log("Odd numbers:", oddNumbers);
console.log("Separated array:", separated);
Even numbers: [ 2, 6, 8, 4, 6, 2, 4 ]
Odd numbers: [ 3, 7, 3, 5, 3, 87, 23, 23, 67 ]
Separated array: [
  2, 6, 8, 4,  6,  2,  4,
  3, 7, 3, 5,  3, 87, 23,
  23, 67
]

Comparison

Method Time Complexity Space Complexity In-place?
Custom Sort O(n log n) O(1) Yes
Filter Method O(n) O(n) No

How the Sort Function Works

The comparator function returns:

  • -1: First element comes before second
  • 1: Second element comes before first
  • 0: Elements are equal (maintain original order)

Conclusion

Use custom sorting for in-place separation with Array.sort(). The filter method is more readable but creates new arrays, using additional memory space.

Updated on: 2026-03-15T23:18:59+05:30

821 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements