Sort a string alphabetically using a function in JavaScript
Last Updated :
20 Dec, 2023
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.
These are the following methods:
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
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
Lodash _.sortBy() method help us to sort the given string alphabetically.
Example: In this example, we are using Lodash _.sortBy() method.
Javascript
const _ = require( 'lodash' );
let randomWord = "sdfjwefic" ;
const sortedStr = _.sortBy([...randomWord]).join( "" );
console.log(sortedStr);
|
Output:
cdeffijsw
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...