How to sort an array of strings in JavaScript?

October 28, 2020 - 3 min read

To sort an array of strings in JavaScript, you can use the sort() method on the array object.

// sort array
arr.sort();

Sort the array in ascending order

By default, the sort() method sorts the array in ascending order.

// array of strings
const strArr = ["Helen", "Jack", "Andrew", "Bob"];

// sort array
// in ascending order
strArr.sort();

console.log(strArr); // ["Andrew", "Bob", "Helen", "Jack"]

See this example live in JSBin.

Sort the array in descending order

To sort the array in descending order, you can pass a function to the sort() method to customize its behavior.

This function will get executed on each iteration while sorting the array and will be passed 2 elements,

  • The first element is the second element of the current iteration
  • The second element is the first element of the current iteration.

Weird. Right! 💀

All we have to is check if the second element is greater than the first element and return:

  • -1 if the second element is greater than the first element
  • 1 if the second element is not greater than the first element
  • 0 to leave both the elements unchanged

Put simply, Returning -1 from the function means to swap the element, and 1 means to not swap the elements.

It can be done like this,

// array of strings
const strArr = ["Helen", "Jack", "Andrew", "Bob"];

// sort array
// in descending order
strArr.sort((a, b) => {
  // convert the elements
  // to lowercase so that we do not
  // have any problem while sorting
  // since capital and small letters
  // have different ascii values
  const aLower = a.toLowerCase();
  const bLower = b.toLowerCase();

  if (aLower > bLower) {
    return -1;
  }

  if (aLower < bLower) {
    return 1;
  }

  return 0;
});

console.log(strArr); // ["Jack", "Helen", "Bob", "Andrew"]

See this example in JSBin.

Some resources if you want to get more information on using various sorting algorithms in JavaScript:

  • Bubble sort algorithm in JavaScript

  • Insertion sort algorithm in JavaScript

  • Selection sort in JavaScript

  • Merge Sort in JavaScript

  • Radix sort in JavaScript

  • Bucket sort in javascript

  • Shell sort in JavaScript

  • Heap sort in JavaScript

  • Counting sort in JavaScript

  • Feel free to share if you found this useful 😃.