Sort the numbers so that the even numbers are ahead JavaScript

We have an array of numbers that contains some positive and negative even and odd numbers. We need to sort the array in ascending order but with a special requirement: all even numbers should appear before any odd number, and both groups should be sorted internally in ascending order.

For example, if we have an array like [-2, 3, 6, -12, 9, 2, -4, -11, -8], the result should be [-12, -8, -4, -2, 2, 6, -11, 3, 9].

How It Works

The solution uses a custom comparator function that:

  • Checks if numbers are even using the modulo operator (% 2)
  • Prioritizes even numbers over odd numbers
  • Sorts numbers within the same parity (even/odd) in ascending order

Example

const arr = [-2, 3, 6, -12, 9, 2, -4, -11, -8];

const sorter = (a, b) => {
    const isAEven = !(a % 2);
    const isBEven = !(b % 2);
    
    // If a is even and b is odd, a comes first
    if (isAEven && !isBEven) {
        return -1;
    }
    
    // If a is odd and b is even, b comes first
    if (!isAEven && isBEven) {
        return 1;
    }
    
    // If both have same parity, sort in ascending order
    return a - b;
};

arr.sort(sorter);
console.log(arr);
[
  -12, -8, -4, -2, 2,
  6, -11, 3, 9
]

Alternative Approach: Using Separate Arrays

const arr2 = [-2, 3, 6, -12, 9, 2, -4, -11, -8];

// Separate even and odd numbers
const evenNumbers = arr2.filter(num => num % 2 === 0).sort((a, b) => a - b);
const oddNumbers = arr2.filter(num => num % 2 !== 0).sort((a, b) => a - b);

// Combine them
const result = [...evenNumbers, ...oddNumbers];
console.log(result);
[
  -12, -8, -4, -2, 2,
  6, -11, 3, 9
]

Comparison

Method Performance Readability Memory Usage
Custom Comparator O(n log n) Good In-place sorting
Separate Arrays O(n log n) Excellent Extra arrays needed

Conclusion

Both approaches effectively sort numbers with even values first. The custom comparator is more memory-efficient, while the separate arrays method is more readable and easier to understand.

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

270 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements