Sort an Array Alphabetically in Javascript



To Sort an Array Alphabetically, we have a sort() method in JavaScript arrays that sorts the array items into an alphabetical order. The sort() method accepts an optional argument as a function that compares two elements of the array.

Following is the syntax of the sort() method:

Array.sort([function to compare ])

If we leave the compare function, then the sort() method will sort the array based on the array values.

Following are the rules for compare function:

  1. If compare (a,b) is less than zero(negative), then the first argument a is less than second argument b (should be placed before the second in resulting array).
  2. If compare (a,b) is greater than zero(positive), then the first argument a is greater than second argument b (should be placed after second one)
  3. If compare (a,b) returns zero, the sort() method considers a equals b and no change in their position.

Sort an array Alphabetically

To sort the elements of the nonSortedArray array in ascending order alphabetically, we can use the sort() method with the compare function as in the example. We can use sort() method without the compare function also.

var nonSortedArray = ['hi', 'yo', 'whatup', 'bye', 'lol'];
var sortedArray = nonSortedArray.sort(function (a, b) {
      if (a < b) return -1;
      else if (a > b) return 1;
      return 0;
    });
console.log(sortedArray); // ["bye", "hi", "lol", "whatup", "yo"]

To sort the nonSortedArray array in descending order, you will need to change the logic of the compare function and pass it to the sort() method as the following example.

var nonSortedArray = ['hi', 'yo', 'whatup', 'bye', 'lol'];
var reverseSortedArray = nonSortedArray.sort(function (a, b) {
      if (a > b) return -1;
      else if (a < b) return 1;
      return 0;
    });
console.log(reverseSortedArray); // ["yo", "whatup", "lol", "hi", "bye"]