JavaScript provides built-in methods to sort the elements of an array. Understanding how these methods work is crucial, as their default behavior can sometimes be surprising.
sort() MethodThe sort() method sorts the elements of an array in place (meaning it modifies the original array) and returns the sorted array.
By default, sort() sorts values as strings. This works well for strings ("Apple" comes before "Banana").
const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort();console.log(fruits); // ["Apple", "Banana", "Mango", "Orange"]
Because sort() treats elements as strings by default, it can produce incorrect results when sorting numbers. For example, "25" is greater than "100" alphabetically because "2" is greater than "1".
const points = [40, 100, 1, 5, 25, 10]; points.sort();console.log(points); // [1, 10, 100, 25, 40, 5] (Incorrect!)
To sort numbers correctly, you must provide a compare function as an argument to the sort() method.
The compare function should return a negative, zero, or positive value, depending on the arguments:
function(a, b){return a - b}
a - b returns a negative value, a is sorted before b.a - b returns a positive value, b is sorted before a.a - b returns 0, the order of a and b is unchanged.const points = [40, 100, 1, 5, 25, 10];// Sort ascending points.sort(function(a, b){return a - b});
console.log(points); // [1, 5, 10, 25, 40, 100]
To sort in descending order, simply reverse the subtraction: function(a, b){return b - a}.
reverse() MethodThe reverse() method reverses the order of the elements in an array. It also modifies the array in place.
const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.reverse();console.log(fruits); // ["Mango", "Apple", "Orange", "Banana"]
You can combine sort() and reverse() to easily achieve a descending sort for strings.
How do you correctly sort the array `[10, 2, 1]` in ascending numerical order?