This post is a part of the JavaScript coding practice series. How to sort string letters in alphabetical order using JavaScript is a common questions in many of the JavaScript & front end development interviews. In this tutorial, you’ll learn how to go about sorting string letters in alphabetical order using JavaScript via two different approaches.

Sorting String Letters In Alphabetical Order

Problem : Sort String letters In Alphabetical Order

By Comparing ASCII code

Approach : Comparing the ASCII code to sort the string letters using JavaScript

For sorting string letters in alphabetical order, first you’ll split the string into an array. Then you need to iterate the array and compare each element with the rest of the other elements on the array. If an element with ASCII code greater than the other element is found, you need to swap the elements. Follow the same approach for all the elements and when iterated over the whole array you’ll have a string with letters sorted in alphabetical order.

Here is how the JavaScript function to sort string letters looks like:

function sortString(str){
  var arr = str.split('');
  var tmp;
  for(var i = 0; i < arr.length; i++){
    for(var j = i + 1; j < arr.length; j++){
      /* if ASCII code greater then swap the elements position*/
      if(arr[i] > arr[j]){
        tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
      }
    }
  }
  return arr.join('');
}

By Using Array.sort Method

Approach : Sorting String Letters Using the JavaScript Array.sort Method.

Here is how the code looks:

function sortString(str){
  var arr = str.split('');
  var sorted = arr.sort();
  return sorted.join('');
}

Wrapping It Up

In this part of the JavaScript coding practice series, you learnt how to go about sorting string letters in alphabetical order using JavaScript. You learnt about two approaches to solving the above problem. One of the methods is using the JavaScript Array.sort method and the other method is by comparing the ASCII code.

How was your experience learning to the solve the above problem? Did you find any issues or corner with the above code? Do you know of any other ways of solving the above issue ? We would love to hear. Do let us know your thoughts and suggestions in the comments below.