Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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];
Expected Output
Then the output should be ?
[2, 2, 6, 8, 1, 5, 7, 9]
Using Custom Comparator Function
We can solve this by creating a custom comparator function that handles both even/odd separation and sorting within each group:
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; // a (even) comes before b (odd)
};
if(!isEven(a) && isEven(b)){
return 1; // b (even) comes before a (odd)
};
return a - b; // same parity, sort numerically
});
const oddEvenSort = arr => {
arr.sort(sorter);
};
oddEvenSort(arr);
console.log(arr);
[
2, 2, 6, 8,
1, 5, 7, 9
]
How It Works
The custom comparator function works as follows:
- If one number is even and the other is odd, the even number comes first
- If both numbers have the same parity (both even or both odd), they are sorted in ascending numerical order
- The
sort()method modifies the original array in place
Alternative Approach: Separate and Combine
Here's another approach that separates even and odd numbers into different arrays, sorts them individually, and then combines them:
const arr2 = [2, 5, 2, 6, 7, 1, 8, 9];
const oddEvenSortAlternate = arr => {
const evens = arr.filter(num => num % 2 === 0).sort((a, b) => a - b);
const odds = arr.filter(num => num % 2 !== 0).sort((a, b) => a - b);
return [...evens, ...odds];
};
const result = oddEvenSortAlternate(arr2);
console.log(result);
[
2, 2, 6, 8,
1, 5, 7, 9
]
Comparison
| Method | Modifies Original? | Time Complexity | Space Complexity |
|---|---|---|---|
| Custom Comparator | Yes | O(n log n) | O(1) |
| Separate and Combine | No | O(n log n) | O(n) |
Conclusion
Both approaches achieve the same result. Use the custom comparator for in-place sorting, or the filter approach when you need to preserve the original array. The custom comparator is more memory-efficient for large arrays.
