How to sort strings in JavaScript?


The sorting string is to arrange strings in the dictionary or alphabetical order. It is usual to sort the array of strings while developing applications using JavaScript. In this tutorial, we will learn to sort strings in JavaScript.

For example, string sorting is very useful here if you got some data from the API and want to show that data in the sorted order.

Here, we will learn to sort strings using the built-in methods and various naïve approaches.

Use the sort() method to sort strings

In JavaScript, sort() is the built-in method we can use with the array. Generally, in other programming languages, the sort() method sorts the number values by default. But, JavaScript converts the numbers into a string and sorts them alphabetically.

So, we can use the sort() method of JavaScript without using the comparator function to sort the array of strings.

Syntax

Users can follow the syntax below to sort the string using JavaScript's sort() method.

Strings.sort();

In the above syntax, we used the array of strings as a reference and the sort() method.

Example 1

In this example, we have defined the strings array and initialized it with some string values. After that, we took the array as a reference and executed the sort() method for the array. Users can observe the output that all strings in the array are sorted in alphabetical order.

<html>
<body>
   <h2>Using the <i>sort() method</i> to sort an array of strings in JavaScript.</h2>
  <div id = "output"> </div>
  <script>
      let output = document.getElementById('output');
      let strings = ["Hi", "JavaScript", "TypeScript", "C", "CPP", "Python", "Java", "HTML", "CSS"];
      output.innerHTML += "The original string array is " + strings + "<br/>";
      strings.sort();
      output.innerHTML += "The sorted string array is " + strings + "<br/>";
   </script>
</body>
</html>

Use the for loop to sort strings (Bubble sort Algorithm)

The naïve approach to sorting the strings is using the for-loop. We can use the two nested for-loop to compare every string with all other strings and sort them in alphabetical order. Also, we can say it is a bubble sort algorithm.

Syntax

Users can follow the syntax below to use the bubble sort algorithm to sort strings in alphabetical order.

for (let a = 0; a < strings.length; a++) {
   for (let b = a + 1; b < strings.length; b++) {
      if (strings[a] > strings[b]) {
         // swap strings at index a and index b
      }
   }
}

In the above syntax, we have used two nested for-loops and iterated through the array of strings. Also, we are comparing the two string values, and based on that, we are swapping the strings.

Algorithm

Step 1Create the array of strings.

Step 2 − Use the for-loop and start iterating through the string array from the 0th index.

Step 3 − In the for-loop, use another for-loop, and start iterating through the a+1th index, when a is the iteration pointer of the first for-loop.

Step 4 − Now, compare the string at the ath and bth indexes.

Step 5 − If the alphabetical order of the string at the ath index is greater than that at the bth index, swap both strings.

Step 6 − Complete all iterations of both for-loop to get all strings in the sorted order.

Example 2 (Considering the case of string characters)

In the example below, we have implemented the bubble-sort algorithm to sort the string array. The below output shows us that the bubble-sort algorithm sorts all strings with an uppercase letter before a lowercase letter, as uppercase letters get higher priority than lowercase letters in string comparison.

<html>
<body>
   <h2>Using the <i> bubble sort algorithm </i> to sort an array of strings in JavaScript.</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');

      let strings = ["car", "Bike", "truck", "cycle", "Tempo", "cart", "abcd", "string"];
      output.innerHTML += "The original string array is " + strings + "<br/>";

      for (let a = 0; a < strings.length; a++) {
         for (let b = a + 1; b < strings.length; b++) {
            if (strings[a] > strings[b]) {
               let tempString = strings[a];
               strings[a] = strings[b];
               strings[b] = tempString;
            }
         }
      }  
      output.innerHTML += "The sorted string array is " + strings + "<br/>";
   </script>
</body>
</html>

Example 3 (Ignoring the case of string characters)

In this example, we have implemented the bubble-sort algorithm to sort strings, but we are comparing the strings in lowercase. In the above example, we sorted the strings according to the alphabetical order and prioritized strings with a capital case. But here, we are ignoring the case of string characters and comparing the strings.

<html>
<body>
   <h2>Using the <i> bubble sort algorithm </i> to sort an array of strings in JavaScript.</h2>
   <div id = "output"> </div>
   <button onclick = "sortStrings()"> Sort Strings </button>
   <script>
      let output = document.getElementById('output');

      let strings = ["ab", "Bc", "AB", "AC", "cd", "ds", "ds", "erere", "DS"];
      output.innerHTML += "The original strings are " + strings + "<br/>";

      function sortStrings() {
         function swap(index1, index2) {
            let tempString = strings[index1];
            strings[index1] = strings[index2];
            strings[index2] = tempString;
         }

         for (let a = 0; a < strings.length; a++) {
            for (let b = a + 1; b < strings.length; b++) {
               if (strings[a].toLowerCase() > strings[b].toLowerCase()) {
                  swap(a, b)
               }
            }
         }
         output.innerHTML += "The sorted strings are " + strings + "<br/>";
      }
   </script>
</body>
</html>

We learned to sort multiple strings in this tutorial. In the first approach, we have used the sort() method, as it always sorts the string in alphabetical order. In the second approach, we have implemented the bubble-sort algorithm to sort strings, but we can optimize it to make it time efficient. Also, we can use other algorithms like merge sort to make our sorting algorithm time and space efficient.

Updated on: 14-Sep-2023

26K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements