An array.sort()
function is used to sort an array in JavaScript. By default, it sorts the array in ascending order.
array.sort()
is called on the array we want to sort. However, by default, it considers the elements of the array as strings; “100” is lower than “50” because “1” comes before “5”.
To avoid this, an optional argument, which is a user-defined compare function
, can be passed to this function.
In case we pass this optional parameter, the sort()
method takes the value at index 0 as a
and every other value one by one as b
to pass on to this compare function. Sorting is then done based on its return value:
a
is placed before b
.a
is placed after b
.The example below shows a numeric array sorted with and without a compare function:
var numbers = [50, 100, 2, 0];// Without compare functionconsole.log("Without compare function:");numbers.sort();console.log(numbers);// With a compare functionconsole.log("With a compare function:");numbers.sort(function(a, b){return a - b;});console.log(numbers);