- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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 are required to sort the array in ascending order but all the even numbers should appear before any of the odd number and all the odd numbers should appear after all the even numbers and obviously both sorted within.

Therefore, for example −

If the input array is −

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

Then the output should be −

[ -12, -8, -4, -2, 2, 6, -11, 3, 9]

Therefore, let’s write the code for this sort function −

## 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(isAEven && !isBEven){ return -1; }; if(!isAEven && isBEven){ return 1; }; return a - b; }; arr.sort(sorter); console.log(arr);

## Output

The output in the console will be −

[ -12, -8, -4, -2, 2, 6, -11, 3, 9 ]

- Related Questions & Answers
- PHP program to find the average of the first n natural numbers that are even
- Finding all the n digit numbers that have sum of even and odd positioned digits divisible by given numbers - JavaScript
- Adding only odd or even numbers JavaScript
- Fetch Numbers with Even Number of Digits JavaScript
- Even numbers at even index and odd numbers at odd index in C++
- Repeating only even numbers inside an array in JavaScript
- Finding even length numbers from an array in JavaScript
- MySQL - Select dates that are one week ahead from today?
- Add minimum number to an array so that the sum becomes even in C++?
- How to generate the first 100 even Numbers using C#?
- Find the count of maximum contiguous Even numbers in C++
- Average of even numbers till a given even number?
- Are array of numbers equal - JavaScript
- Find the primorial of numbers - JavaScript
- Add minimum number to an array so that the sum becomes even in C programming

Advertisements