Open In App

Sort a string in JavaScript

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:



Approach 1: Using the sort() function

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"));

Output
Sorted String: 
eiopqrtuwy

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

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"));

Output
Sorted String: 
eiopqrtuwy

Article Tags :