Sort a string alphabetically by creating a user-defined function to perform sorting. This function is useful when we receive a random set of characters as a string and we want it to be sorted in an alphabetical manner. To perform this task we will use multiple inbuilt methods and combine them to create a helper function.
- Using split() method, sort() method and join() method
- Using spread operator, sort() method and localeCompare()
Approach 1: Using split() method, sort() method and join() method
- Step 1: Convert the string into an array using split() method.
- Step 2: Sort the array using the sort() method
- Step 3: Convert the sorted array back to String using join() method.
Note: We will use the concept of method chaining to reduce the lines of code.
Example: In this example, we will implement the above approach.
Javascript
function sortAlpha(word) { return word.split( "" ) .sort() .join( "" ); } let randomWord = "sdfjwefic" ; console.log(sortAlpha(randomWord)) |
Output:
cdeffijsw
Approach 2: Using spread operator, sort() method and localeCompare()
- Step 1: Destructure the string into an array using the spread operator
- Step 2: Sort the array by passing a callback function inside sort() method
- Step 3: Use the inbuilt localeCompare() and join() methods to return the sorted String
Example: We will use the method chaining and arrow function syntax to make the code short and readable.
Javascript
function sortAlpha(word) { return [...word].sort((a,b)=>a.localeCompare(b)).join( "" ) } let randomWord = "sdFjwefiC" ; console.log(sortAlpha(randomWord)); |
Output:
CdefFijsw