.sort()
MethodThe native sort()
method sorts the elements of an array "in place" and returns the sorted array
in-place
means no copy
is made// string sort const months = ['March', 'Jan', 'Feb', 'Dec']; months.sort(); console.log(months); // ["Dec", "Feb", "Jan", "March"]; // number sort const array1 = [1, 30, 4, 21, 100000]; array1.sort(); console.log(array1); // [1, 100000, 21, 30, 4];
The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.
The default sort order is ascending
strings
UTF-16
code units valuesTo compare numbers instead of strings, the compare function can subtract b
from a
. The following function will sort the array in ascending order
(if it doesn't contain Infinity
and/or NaN
)
function compareNumbers(a, b) { return a - b; } const numbers = [4, 2, 5, 1, 3]; // function expressions numbers.sort(function(a, b) { return a - b; }); console.log(numbers); // [1, 2, 3, 4, 5]; // arrow function numbers.sort((a, b) => a - b); console.log(numbers); // [1, 2, 3, 4, 5];
Array.sort((a,b) ⇒ (a-b))
sorts numbersThe function that you pass tells how to sort the elements
(a, b)
that represent any two elements from the arrayHow the elements will be sorted depends on the function’s return value
negative value
, the value in a
will be ordered before b
0
, the ordering of a
and b
won’t changepositive value
, the value in b
will be ordered before a
function compare(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; }
For sorting strings with non-ASCII
characters, i.e. strings with accented characters (e
, é
, è
, a
, ä
, etc.), strings from languages other than English, use String.localeCompare
const items = ['réservé', 'premier', 'communiqué', 'café', 'adieu', 'éclair']; items.sort(function (a, b) { return a.localeCompare(b); }); console.log(items); // ['adieu', 'café', 'communiqué', 'éclair', 'premier', 'réservé'];
Arrays of objects can be sorted by comparing the value of one of their properties
var items = [ { name: 'Edward', value: 21 }, { name: 'Sharpe', value: 37 }, { name: 'And', value: 45 }, { name: 'The', value: -12 }, { name: 'Magnetic', value: 13 }, { name: 'Zeros', value: 37 } ]; // sort by value items.sort(function (a, b) { return a.value - b.value; }); // sort by name items.sort(function(a, b) { var nameA = a.name.toUpperCase(); // ignore upper and lowercase var nameB = b.name.toUpperCase(); // ignore upper and lowercase if (nameA < nameB) { return -1; } if (nameA > nameB) { return 1; } // names must be equal return 0; });