Sorting Arrays (and a Sneaky Surprise)

Grade 7, page 11 of 14. A one-minute read.

The sort() method puts an array in order. With strings, it sorts alphabetically:

JavaScript
const names = ["Omar", "Mia", "Sam", "Zoe"];
names.sort();
console.log(names);

It prints

[ 'Mia', 'Omar', 'Sam', 'Zoe' ]

Easy. Now let's sort some numbers:

JavaScript
const numbers = [10, 1, 5, 100, 25];
numbers.sort();
console.log(numbers);

It prints

[ 1, 10, 100, 25, 5 ]

Wait, what? 100 comes before 25? And 5 is last?

Watch outsort() treats everything as text

By default, sort() converts every item to a string and sorts them alphabetically, even numbers! As text, "100" comes before "25" because "1" comes before "2", the same way "apple" comes before "banana." To sort numbers properly, you need to give sort a little comparison function:

JavaScript
const numbers = [10, 1, 5, 100, 25];

numbers.sort((a, b) => a - b);
console.log(numbers);

numbers.sort((a, b) => b - a);
console.log(numbers);

It prints

[ 1, 5, 10, 25, 100 ]
[ 100, 25, 10, 5, 1 ]

(a, b) => a - b sorts from smallest to largest, and (a, b) => b - a sorts from largest to smallest. Just memorize these two for now. We'll explain exactly how they work in Grade 10.

Also note that sort() and reverse() change the original array. If you want to keep the original order safe, sort a copy: [...numbers].sort((a, b) => a - b). (Newer versions of JavaScript also have toSorted() and toReversed(), which return a new array and leave the original alone.)

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning