Sort three numbers in JavaScript
Beginner · 3 min read
Putting numbers in order is something almost every app does: prices from low to high, scores from best to worst, dates from oldest to newest. JavaScript arrays have a built-in sort method, so this should be a one-liner. It is, but the obvious way of calling it gives wrong answers for numbers, and this lesson shows you why.
You will write sortThree(a, b, c), which returns the three numbers in ascending order (smallest first). You need to know what a function and an array are. How sort works is explained from zero.
How sort decides the order
sort compares pairs of items and moves them around until the whole array is in order. The question is how it compares. If you don't tell it, sort turns every item into text and puts them in dictionary order, the way words are ordered in a dictionary.
For words that is what you want. For numbers it isn't. As text, '10' comes before '9', because the first character '1' comes before '9', the same way "apple" comes before "banana" no matter how long the words are.
The compare function
You can pass sort your own compare function. It receives two items, a and b, and returns a number:
- negative:
agoes first - positive:
bgoes first - zero: leave them as they are
For numbers, a - b gives exactly that. If a is smaller, a - b is negative, so a goes first.
Here is the exercise. Try it yourself first if you like, then follow along.
17 Sort three numbers
easyTake three numbers and return them in ascending order. Then note what goes wrong if you sort numbers the obvious way.
Stuck? Three hints, smallest first
- 1.
[3, 1, 2].sort()works.[10, 9].sort()does not. - 2.
sort()with no argument compares values as text, so10sorts before9. - 3. Always pass a comparator for numbers:
sort((a, b) => a - b).
Step 1: the obvious way
Put the three numbers in an array and sort it.
console.log([3, 1, 2].sort()); // [ 1, 2, 3 ]
That looks fine. Now try numbers with different numbers of digits:
console.log([10, 9, 100, 1].sort()); // [ 1, 10, 100, 9 ]
9 ended up last. As text, '1', '10' and '100' all start with 1, so they come before '9'. With single digits the bug hides, which is why it gets into real code.
Step 2: pass a compare function
function sortThree(a, b, c) {
return [a, b, c].sort((x, y) => x - y);
}
console.log(sortThree(3, 1, 2)); // [ 1, 2, 3 ]
console.log(sortThree(10, 9, 100)); // [ 9, 10, 100 ]
console.log(sortThree(0, -5, 5)); // [ -5, 0, 5 ]
console.log(sortThree(2, 2, 1)); // [ 1, 2, 2 ]
The parameter names x and y are used inside the arrow so they don't get confused with a, b and c. Negative numbers work, and duplicates are kept.
For largest first, swap the subtraction: (x, y) => y - x.
Step 3: sort changes the array
There is a second surprise. sort doesn't make a new array. It rearranges the one you call it on and then returns that same array.
const original = [3, 1, 2];
const sorted = original.sort((a, b) => a - b);
console.log(original); // [ 1, 2, 3 ]
console.log(original === sorted); // true
original has been reordered too, and === confirms the two names point to the same array. In sortThree this is fine, because the array is brand new each time. But if you sort an array that other code is still using, you change it under its feet.
Step 4: sort a copy
slice() with no arguments copies the whole array. Sort the copy and the original stays as it was.
const numbers = [10, 9, 100, 1];
const inOrder = numbers.slice().sort((a, b) => a - b);
console.log(inOrder); // [ 1, 9, 10, 100 ]
console.log(numbers); // [ 10, 9, 100, 1 ]
Newer JavaScript versions also have toSorted(), which returns a sorted copy without touching the original.
The full solution
The complete answer sorts two sets of three numbers, shows the same list sorted with and without a compare function, and proves that sort returns the very array it changed. Press Run to see the output.
function sortThree(a, b, c) {
return [a, b, c].sort((x, y) => x - y); // the comparator is not optional
}
console.log(sortThree(3, 1, 2));
console.log(sortThree(10, 9, 100));
// The default sort compares as text, which is almost never what you want:
const numbers = [10, 9, 100, 1];
console.log('with a comparator:', numbers.slice().sort((a, b) => a - b));
console.log('without one :', numbers.slice().sort());
// And sort mutates, which surprises people. slice() above is what protects it.
const original = [3, 1, 2];
const sorted = original.sort((a, b) => a - b);
console.log('same array?', original === sorted);
Output
6 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 6 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('three in order', sortThree(3, 1, 2), [1, 2, 3]);
test('two digits sort correctly with a comparator', sortThree(10, 9, 100), [9, 10, 100]);
test('the default sort gets it wrong', [10, 9, 100, 1].sort(), [1, 10, 100, 9]);
test('negatives', sortThree(0, -5, 5), [-5, 0, 5]);
test('duplicates are kept', sortThree(2, 2, 1), [1, 2, 2]);
test('sort returns the same array it mutated', original === sorted, true);
Two things bite here. sort() with no comparator converts everything to text, so [10, 9] becomes [10, 9] because "10" < "9" — the third assertion pins that down. And sort changes the array in place and returns the very same array, which is why the examples above use slice() first. Both are decades-old design choices you simply have to know.
Common mistakes
- Calling
sort()with no compare function on numbers. It sorts as text, so 10 comes before 9. - Returning
trueorfalsefrom the compare function.(a, b) => a > bdoesn't give the negative numbersortneeds. Returna - b. - Forgetting that
sortchanges the array. Copy it first withslice()if the original order still matters.
Try it yourself
- Change
sortThreeto return the numbers largest first. - Sort
['banana', 'Apple', 'cherry']. Where does'Apple'end up, and why? (Capital letters come before lowercase in text order.) - Write
median(a, b, c)that returns the middle value of three numbers usingsortThree.