Sort a String in JavaScript
Here are the most used methods to sort characters in a string using JavaScript.
Using split(), sort(), and join()
The most simple way to sort a string is to first convert it to an array of characters, sort the array, and then join it back into a string.
let s1 = "javascript";
let s2 = s1.split('').sort().join('');
console.log(s2);
Output
aacijprstv
Using Array.from() with sort()
Similar to split(), you can also use Array.from() to convert the string to an array of characters, then apply sort() and join() to get the sorted result.
let s1 = "javascript";
let s2 = Array.from(s1).sort().join('');
console.log(s2);
Output
aacijprstv
Using a for Loop and Custom Sorting
For custom sorting (e.g., sorting by frequency, case-insensitivity), you can convert the string to an array and use a for loop to implement custom sorting logic.
let s1 = "JavaScript";
let s2 = s1
.split("")
.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }))
.join("");
console.log(s2);
Output
aaciJprStv
Using reduce() with Sorting Logic
If you need more complex sorting, reduce() can help by building a sorted string as it processes each character, but this approach is less efficient and less commonly used.
let s1 = "javascript";
let s2 = s1
.split("")
.reduce((acc, char) => acc + char, "")
.split("")
.sort()
.join("");
console.log(s2);
Output
aacijprstv
The split(), sort(), and join() approach is the most popular and efficient for basic character sorting in a string.
Please refer Sort a String for different algorithms and their complexities to sort a string.