The .sort() method sorts the elements of an array. The default method will sort the array according to string Unicode code points. To sort an array numerically the .sort() method needs to have a compareFunction passed to it.

Note: The .sort() method is impure. .sort() will sort the array in-place, i.e., instead of creating a sorted copy of the original array, it will re-order the original array and return it.

Default Sort

Sorts the array in UNICODE order.

['s', 't', 'a', 34, 'K', 'o', 'v', 'E', 'r', '2', '4', 'o', 'W', -1, '-4'].sort();

Results in:

[-1, '-4', '2', 34, '4', 'E', 'K', 'W', 'a', 'l', 'o', 'o', 'r', 's', 't', 'v']

Note: The uppercase characters have moved above lowercase. The array is not in alphabetical order, and numbers are not in numerical order.

Alphabetical Sort

['s', 't', 'a', 'c', 'K', 'o', 'v', 'E', 'r', 'f', 'l', 'W', '2', '1'].sort((a, b) => {
  return a.localeCompare(b);        
});

Results in:

['1', '2', 'a', 'c', 'E', 'f', 'K', 'l', 'o', 'r', 's', 't', 'v', 'W']

Note: The above sort will throw an error if any array items are not a string. If you know that the array may contain items that are not strings use the safe version below.

['s', 't', 'a', 'c', 'K', 1, 'v', 'E', 'r', 'f', 'l', 'o', 'W'].sort((a, b) => {
  return a.toString().localeCompare(b);      
});

String sorting by length (longest first)

["zebras", "dogs", "elephants", "penguins"].sort(function(a, b) {
  return b.length - a.length;
});

Results in

["elephants", "penguins", "zebras", "dogs"];

String sorting by length (shortest first)

["zebras", "dogs", "elephants", "penguins"].sort(function(a, b) {
  return a.length - b.length;
});