Array.prototype.sort()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The sort() method of Array instances sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code unit values.
The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.
To sort the elements in an array without mutating the original array, use toSorted().
Try it
const months = ["March", "Jan", "Feb", "Dec"];
months.sort();
console.log(months);
// Expected output: Array ["Dec", "Feb", "Jan", "March"]
const array = [1, 30, 4, 21, 100000];
array.sort();
console.log(array);
// Expected output: Array [1, 100000, 21, 30, 4]
Syntax
sort()
sort(compareFn)
Parameters
compareFnOptional-
A function that determines the order of the elements. The function is called with the following arguments:
a-
The first element for comparison. Will never be
undefined. b-
The second element for comparison. Will never be
undefined.
It should return a number where:
- A negative value indicates that
ashould come beforeb. - A positive value indicates that
ashould come afterb. - Zero or
NaNindicates thataandbare considered equal.
To memorize this, remember that
(a, b) => a - bsorts numbers in ascending order.If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.