W3docs

How to Sort Array Alphabetically in JavaScript

Read this JavaScript tutorial and learn the two methods of sorting the elements of an array in alphabetical order based on the values of the elements.

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

Note: The sort() method mutates the original array in place.

The <kbd class="highlighted">sort( )</kbd> method accepts an optional compare function that defines how two elements should be compared.

Sorting an array alphabetically

javascript— editable

The <kbd class="highlighted">sort( )</kbd> method will sort the items based on their string values when the compare function is omitted:

  • If the compare function returns a negative value, <kbd class="highlighted">a</kbd> is sorted to a lower index than <kbd class="highlighted">b</kbd>.
  • If it returns a positive value, <kbd class="highlighted">b</kbd> is sorted to a lower index than <kbd class="highlighted">a</kbd>.
  • If it returns zero, their relative order is preserved.

Suppose you have two elements a and b and want to compare <kbd class="highlighted">a.firstname</kbd> and <kbd class="highlighted">b.firstname</kbd>, then act as follows:

Sorting objects alphabetically

javascript— editable

If compared strings contain Unicode characters, you can use the <kbd class="highlighted">localeCompare()</kbd> function, which has built-in support for language-specific sort ordering, ignoring cases, diacritics, and symbols like ß:

Using localeCompare() for Unicode strings

javascript— editable

The sort() Method

The <kbd class="highlighted">sort( )</kbd> 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 <kbd class="highlighted">sort( )</kbd> method sorts numbers in the following order: "35" is bigger than "225", because "3" is bigger than "2".

The localeCompare() method

The <kbd class="highlighted">localeCompare()</kbd> 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.