Odds and Evens

A typical question asked in "History of JavaScript" classes where the teacher mistakenly believes they are teaching programming.


Write a function to sort this array: 45, 23, 12, 11, 7, 56, 54, 43, 22, 9, 11, 27, 38, 93, 43
so that the function will return this array: 12, 22, 38, 54, 56, 7, 9, 11, 11, 23, 27, 43, 43, 45, 93

Historical Answer:

I can't even imagine what the code most people trying to use JavaScript to answer this question would produce if they don't know about overriding the sort comparison function in JavaScript. Presumably they would eventually recognise that they are being asked to sort all the even numbers first followed by the odd numbers with those in each group in ascending numerical order. Perhaps they's start by splitting the array into two separate arrays - one for the even numbers and a second for the odd numbers. They might then convert all the single digit numbers to strings to add a leading zero before sorting each array and then joining them back together into a single array.

JavaScript Answer:

evenOddSplit = function(a, b) {
if (a % 2 === b % 2) return a - b;
return a % 2 - b % 2;

var input = [45, 23, 12, 11, 7, 56, 54, 43, 22, 9, 11, 27, 38, 93, 43];

This simple function to override the comparison function for the sort allows us to sort the input directly into the required order. The if statement determines if they are both odd or both even and if they are then it orders them numerically. The second return orders the odd number after the even one if there is one of each.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow