JavaScript Array sort() method
sorts the elements of an array

sort() method sorts the elements of an array.

syntax

sort(compareFn)

compareFn (optional). 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 a should come before b

A positive value indicates that a should come after b

Zero or NaN indicates that a and b are considered equal.

To memorize this, remember that (a, b) => a - b sorts numbers in ascending order.

If compareFn is omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.

All undefined elements are sorted to the end of the array and compareFn is not called for them.

sort() method returns the reference to the original array, now sorted.

sort() method changes the position of the elements in the original array.

sort() method compares the elements of the array by converting them into strings and then comparing their Unicode code points.

This can lead to unexpected results when sorting arrays of numbers.

[1, 2, 3, 4, 11, 22].sort(); returns ↴

[1, 11, 2, 22, 3, 4]

To overcome this we can provide a comparison function that defines the desired sorting order.

[1, 2, 3, 4, 11, 22].sort((a, b) => a - b); returns ↴

[1, 2, 3, 4, 11, 22] to sort in ascending order, or

[1, 2, 3, 4, 11, 22].sort((a, b) => b - a); returns ↴

[22, 11, 4, 3, 2, 1] to sort in descending order.

To sort arrays of strings we can also use a comparison function that defines the desired sorting order.

['a', 'A', 'b', 'B', 'c', 'C'].sort(); returns ↴

['A', 'B', 'C', 'a', 'b', 'c']

['a', 'A', 'b', 'B', 'c', 'C'].sort((a, b) => a < b ? -1 : 1); returns ↴

['A', 'B', 'C', 'a', 'b', 'c'] to sort in ascending order, or

['a', 'A', 'b', 'B', 'c', 'C'].sort((a, b) => a > b ? -1:1); returns ↴

['c', 'b', 'a', 'C', 'B', 'A'] to sort in descending order.

An array can also be sorted by comparing the value of one of its properties.

const myArray = ['xx', 'x', 'xxxx', 'xxx'];

myArray.sort((a, b) => a.length > b.length ? 1 : -1); returns ↴

['x', 'xx', 'xxx', 'xxxx'] to sort in ascending order, or

myArray.sort((a, b) => a.length > b.length ? -1 : 1); returns ↴

['xxxx, 'xxx', 'xx', 'x'] to sort in descending order.

sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.

To sort the elements in an array without mutating the original array, use the toSorted() method.

syntax 1 description
sort the elements of myArray
myArray.sort()
syntax 2 description
sort the elements of myArray with a compare function
myArray.sort(compareFn)