Skip to content
Related Articles

Related Articles

Sort string of characters using JavaScript

View Discussion
Improve Article
Save Article
  • Difficulty Level : Expert
  • Last Updated : 06 Jul, 2022
View Discussion
Improve Article
Save Article

In this article, we will try to understand how to sort strings of characters using several different approaches available using JavaScript.

Let us see how to create a string using the syntax provided by JavaScript and thereafter we will see a short example that will help us to understand this syntax clearly.

Syntax:

let string_name = "";

Now let us have a look over the below-shown example which will explain the above syntax more clearly.

Example: In this example, we will simply create a string and will try to perform some operations on it.

Javascript




<script>
let my_string = "banana";
console.log("Fruit name is: " + my_string);
  
console.log("Character at 4th index is : " 
    + my_string.charAt(4));
<script>

Output:

Fruit name is: banana
Character at 4th index is : n

Now let us see our main task which is to sort the string of characters using several approaches available using JavaScript. Following are some of the approaches which will help us to do our task:

Approach 1: Using sort() function

  • In this approach, we will use the split() method in order to convert our string into an array first.
  • We will apply the sort() method on that converted array in order to sort the characters alphabetically.
  • After sorting the characters alphabetically, we will convert our array back into the string itself using the method called join().

Example:

Javascript




<script>
let sortString = (stringg) => {
  return stringg.split("").sort().join("");
};
  
console.log("Sorted String: ");
console.log(sortString("qwertyuiop"));
<script>

Output:

Sorted String: 
eiopqrtuwy

Approach 2: Using sort(), localCompare() and join() methods.

  • We will convert a string into an array itself.
  • We will use an array for the same, and then we will apply the sort() method which will take two parameters that represent two characters.
  • The localCompare() method will compare the two characters and it will be placed first whichever comes first.
  • We will apply the join() method which will join all the characters and make the array return to the string itself.

Example:

Javascript




<script>
let sortString = (str) => {
  return [...str].sort((a, b) => a.localeCompare(b)).join("");
}
  
console.log("Sorted String: ");
console.log(sortString("qwertyuiop"));
<script>

Output:

Sorted String: 
eiopqrtuwy

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!