How to Sort Array Alphabetically in JavaScript

JavaScript arrays have the sort( ) method, which sorts the array elements into alphabetical order.

The sort( ) method accepts a function that compares two items of the Array.sort([comparer]) .

Javascript arrays sort method
let elements = ['Javascript', 'Css', 'Html']; elements.sort(function (a, b) { return a.length - b.length; }); console.log(elements);

The sort( ) method will sort the item based on the values of the elements in case the compare function is omitted:

  • If the comparison is less than zero, the sort( ) method sorts to a lower index than b.
  • If the comparison is greater than zero, the sort( ) method sort b to a lower index than a.
  • If the comparison returns zero, the sort( ) method considers that a equals b and does not change their position.

Suppose you have two elements a and b and want to compare a.firstname and b.firstname, then act as follows:

Javascript arrays sort method
a = { firstname: 'John' }; b = { firstname: 'Jack' }; users = [a, b]; users.sort(function (a, b) { if (a.firstname < b.firstname) { return -1; } if (a.firstname > b.firstname) { return 1; } return 0; }) console.log(users);

If compared strings contain Unicode characters, you can use localeCompare function which has built-in support for language-specific sort ordering, ignoring cases, diacritics, symbols like ß:

Javascript arrays localCompare method
let elements = ['Javascript', 'Css', 'Html']; arr = elements.sort((a, b) => a.localeCompare(b)); console.log(arr);

The sort() Method

The sort( ) method sorts the array elements in place and returns the sorted array. By default, the sort order is ascending, built upon converting the elements into strings and then comparing their sequences of UTF-16 code unit values. Number sorting can be incorrect as the sort( ) method sorts numbers in the following order: "35" is bigger than "225", because "3" is bigger than "2".

The localeCompare() method

The localeCompare() method compares two strings in the current locale. It returns a number which indicates whether an element comes before, after, or is equal to the given string in sort order.