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
Selected Reading
Odd even sort in an array - 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];
Then the output should be ?
const output = [2, 2, 6, 8, 1, 5, 7, 9];
Approach
The solution uses a custom comparator function that:
- Places even numbers before odd numbers
- Sorts even numbers in ascending order among themselves
- Sorts odd numbers in ascending order among themselves
Example
Following is the code ?
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);
[
2, 2, 6, 8,
1, 5, 7, 9
]
How It Works
The comparator function logic:
- If a is even and b is odd: Return -1 (a comes first)
- If a is odd and b is even: Return 1 (b comes first)
- If both have same parity: Return a - b (ascending order)
Alternative Approach
You can also separate the arrays first, then concatenate:
const arr2 = [2, 5, 2, 6, 7, 1, 8, 9];
const oddEvenSortAlternative = 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];
};
console.log(oddEvenSortAlternative(arr2));
[
2, 2, 6, 8,
1, 5, 7, 9
]
Conclusion
Both approaches work effectively. The custom comparator modifies the original array, while the filter approach creates a new sorted array. Choose based on whether you need to preserve the original array.
Advertisements
