Sorting: sort()

The method sort() sorts an array. Unlike filter() and map(), it doesn't create a new array. It sorts the array itself:

const names = ["Leo", "Pip", "Ella", "Gina"];
names.sort();
console.log(names);
["Ella", "Gina", "Leo", "Pip"]

With numbers, though, it has a surprise for you:

const scores = [10, 9, 1];
scores.sort();
console.log(scores);
[1, 10, 9]

That's because sort() compares the elements as texts, character by character, like words in a dictionary. The text "10" starts with "1", so it comes before "9". To sort numbers, give sort() a compare function:

scores.sort((a, b) => a - b);
console.log(scores);
[1, 9, 10]

sort() calls the compare function again and again, each time with two of the elements, a and b. The result tells it which of the two goes first: when it's negative, a does; when it's positive, b does; and when it's 0, they stay as they are. a - b is negative when a is smaller, so the smaller numbers go first. To get the largest first, swap them: (a, b) => b - a.

A compare function can also sort objects by one of their properties. Texts are compared with localeCompare(): a.localeCompare(b) is negative when a comes before b in the alphabet and positive when it comes after it, just like a - b with numbers:

animals.sort((a, b) => a.age - b.age);
console.log(animals.map((animal) => animal.name));

animals.sort((a, b) => a.name.localeCompare(b.name));
console.log(animals.map((animal) => animal.name));
["Pip", "Gina", "Leo", "Ella"]
["Ella", "Gina", "Leo", "Pip"]

Why not use plain sort() for texts? It sorts by the codes of the characters, so all capital letters come before all small ones: ["eva", "Zoe", "Anna"].sort() gives ["Anna", "Zoe", "eva"]. localeCompare() sorts the way people do: Anna, eva, Zoe. And it can sort objects, which plain sort() can't.

A typical mistake is to subtract texts: a.name - b.name gives NaN (Not a Number), and the array stays in the order it was in.

Instructions

Sort times from the fastest time, the smallest number, and print the array: [49, 58, 62, 71, 105].

Below, sort runners by their times, the fastest first, and print their names in this order, separated by commas: Ranking: Mia, Liam, Zoe, Ava, Noah.

Finally, sort runners by their names with localeCompare(), and print the names in alphabetical order: Runners: Ava, Liam, Mia, Noah, Zoe.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

6/10

Next