Sort the numbers so that the even numbers are ahead JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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
]
raja
Published on 25-Aug-2020 06:36:24
Advertisements