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:
Table of Content
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: In this example, we are sorting the given string by the use of the sort() function.
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: In this example, we are sorting the given string by the use of the sort(), localCompare(), and join() functions.
let sortString = (str) => { return [...str].sort((a, b) =>
a.localeCompare(b)).join( "" );
} console.log( "Sorted String: " );
console.log(sortString( "qwertyuiop" ));
|
Sorted String: eiopqrtuwy