Loading lessons...
Array Sort
Array Sort
sort() arranges the items of an array. Be careful: the default sort treats items as text.
The default sort
["cherry", "apple", "banana"].sort();
// ["apple", "banana", "cherry"]
Strings sort alphabetically by default.
The number trap
The default sort converts numbers to strings, so [10, 9, 80] sorts as ["10", "80", "9"]:
[10, 9, 80].sort(); // [10, 80, 9] (wrong order!)
Sort numbers correctly
Provide a compare function:
[10, 9, 80].sort(function(a, b) {
return a - b;
});
// [9, 10, 80]
- Negative result: a goes before b.
- Positive result: b goes before a.
- Zero: they stay.
Sort descending
[10, 9, 80].sort((a, b) => b - a); // [80, 10, 9]
reverse
reverse() flips the order of an array:
[1, 2, 3].reverse(); // [3, 2, 1]
TL;DR
- sort() works well for strings by default.
- Numbers need a compare function (a, b) => a - b.
- reverse() flips the array order.