Sorting is one of the most common operations performed on arrays. JavaScript provides two
fundamental methods for organizing your data: sort() for ordering elements
and reverse() for flipping the order.
By default, the sort() method sorts values as strings in
alphabetical and ascending order.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // ["Apple", "Banana", "Mango", "Orange"]
fruits.reverse(); // ["Orange", "Mango", "Banana", "Apple"]
If numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the standard sort() method will produce an incorrect result
when sorting numbers.
To sort numbers correctly, you must pass a compare function into the
sort() method.
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
// Result: [1, 5, 10, 25, 40, 100]
a - b is negative, a is sorted before
b.b is sorted before a.Arrays often contain objects. You can use the compare function to sort objects by a specific property.
const cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}
];
cars.sort(function(a, b){return a.year - b.year});
sort() method overwrites the original array. If
you want to keep the original array unchanged, use the modern (ES2023)
toSorted() method instead.
Since ES2019, JavaScript's sorting algorithm (Timsort) is stable. This means that elements with equal values will stay in their original relative order after sorting.
sort() is for alphabetical stringssort() modifies the original array (mutates data)reverse() to flip the current order of an arraytoSorted() (ES2023)Math.random() - 0.5 in a compare function for a "random" sort
(shuffling)