# Odd even sort in an array - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

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];

## 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);

## Output

Following is the output in the console −

[
2, 2, 6, 8,
1, 5, 7, 9
]
Updated on 16-Sep-2020 10:10:43