Using the sort() method or Loop you can Sort strings in JavaScript. Use the sort method only when the string is alphabetic.
Sort string in JavaScript
Simple example code Sort string in JavaScript using sort() method.
<!DOCTYPE html>
<html>
<body>
<script>
let student_name = ['Rohit', 'Aman', 'Balu', 'Shweta', 'Diya'];
student_name.sort();
console.log(student_name)
</script>
</body>
</html>
Output:
Sort strings using the loop on strings.
Use a loop and then compare each element and put the string at its correct position.
<script>
function string_sort(str) {
var i = 0, j;
while (i < str.length) {
j = i + 1;
while (j < str.length) {
if (str[j] < str[i]) {
var temp = str[i];
str[i] = str[j];
str[j] = temp;
}
j++;
}
i++;
}
}
let str = ['A', 'C', 'E', 'D', 'B'];
str.sort();
console.log(str)
</script>
Output: [ “A”, “B”, “C”, “D”, “E” ]
Sort Strings using localeCompare() or non-ASCII characters
<script>
let emp = ['nèha', 'hardik', 'éaster', 'chaitanya', 'spain'];
emp.sort(function (str1, str2) {
return str1.localeCompare(str2);
});
console.log(emp)
</script>
Output: [ “chaitanya”, “éaster”, “hardik”, “nèha”, “spain” ]
Do comment if you have any doubts or suggestions on this JS sort topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version