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.
Following are some of the approaches which will help us to do our task:
- Using sort() function
- Using sort(), localCompare() and join() methods.
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
let my_string = "banana" ; console.log( "Fruit name is: " + my_string); console.log( "Character at 4th index is : " + my_string.charAt(4)); |
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.
Approach 1: Using the 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
let sortString = (stringg) => { return stringg.split( "" ).sort().join( "" ); }; console.log( "Sorted String: " ); console.log(sortString( "qwertyuiop" )); |
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
let sortString = (str) => { return [...str].sort((a, b) => a.localeCompare(b)).join( "" ); } console.log( "Sorted String: " ); console.log(sortString( "qwertyuiop" )); |
Sorted String: eiopqrtuwy