Array Sort
Native .sort()
Method
The native sort()
method sorts the elements of an array "in place" and also returns the sorted array.
in-place
meansno 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];
Space/Time Complexity
The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.
Default Behaviors
The default sort order is ascending
- built upon converting the elements into
strings
- then comparing their sequences of
UTF-16
code units values
Sorting Numbers
To 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
)
// ascending (a,b) => a - b; // descending (a,b) => b - a;
Style:
// callback function compareNumbers(a, b) { return a - b; } const numbers = [4, 2, 5, 1, 3]; numbers.sort(compareNumbers); // 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];
How Array.sort((a,b) ⇒ (a-b))
sorts numbers
How the elements will be sorted depends on the callback function’s return value
:
- If it returns a
negative value
, the value ina
will be ordered beforeb
. - if it returns
0
, the ordering ofa
andb
won’t change. - if it returns a
positive value
, the value inb
will be ordered beforea
.
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 equals to b return 0; }
Sorting non-ASCII Characters
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
- This function can compare those characters so they appear in the right order.
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é'];
Sorting Array of Objects
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; });