Updated April 10, 2023
Introduction to Sort string in JavaScript
Sort String in JavaScript is used to sort the strings according to alphabetical order i.e it converts the given elements into strings by comparing the UTF-16 code sequences into unit values. Sorting of strings is a common question in many of the Front-End Developer Interviews, here, we shall see how to go about sorting strings in alphabetical order in JavaScript with various approaches. In JavaScript, we use sort() method to sort the strings and return the sorted array of strings. Default order being ascending order, built upon conversion for elements into strings. Time complexity and space complexity of the sorting can’t be fixed as it depends on the implementation.
Syntax:
Here is the syntax for sorting strings,
As said, the sort() method sorts elements with the smallest value at the start and largest at last.
<array_name>.sort();
Let the student be an array of strings,
student.sort();
There is no need for arguments to be passed to the sort() method.
sort() can have an optional parameter as compareFunction used to define customized sorting order if any.
sort() method returns array after sorting the elements of the array.
How to sort strings in JavaScript?
- We have two ways to sort strings such as Using sort() method or Using Loop.
- On using sort() method, we are using a predefined method by JavaScript to sort array of strings.
- Sort() method is applicable only for alphabetic strings.
- Sort() method does not support array of numbers.
- There is one simple approach in sorting the array of elements i.e. Looping an array and comparing each element to put the string elements at its position.
- Here, Looping can be applied to numbers in an array
Example #1
Simple Sort string in JavaScript using sort() method
Code:
let student_name = ['Karthik', 'Saideep', 'Balu', 'Shweta', 'Diya'];
student_name.sort();
console.log(‘Here are the student name sorted in ascending order by default’, student_name);
Output:
Here we have taken an array of strings, these are sorted using the sort() method in alphabetical order by default.
Example #2
Sort string using for loop on strings.
Code:
<!DOCTYPE html>
<html>
<head>
<body>
<h2>Sort strings using for loop in JavaScript</h2>
<script>
function sortString(strArray) {
var i = 0;
var j;
while (i < strArray.length) {
j = i + 1;
while (j < strArray.length) {
if (strArray[j] < strArray[i]) {
var tempStr = strArray[i];
strArray[i] = strArray[j];
strArray[j] = tempStr;
}
j++;
}
i++;
}
}
var sortArray = ['Karthik', 'Saideep', 'Balu', 'Shweta', 'Divya', 'Bhanu'];
document.write("Original Array of strings</br>");
document.write(sortArray);
document.write("</br>");
sortString(sortArray);
document.write("</br>Array of strings After sorting</br>");
document.write(sortArray);
</script>
</body>
</html>
Output:
So here we are using the for loop to sort the array of strings in ascending order by default. Function sortString accepts the Array ‘sortArray’ as a parameter.
Two variables ‘i’ and ‘j’ let you compare the strings based on the length of the array.
Example #3
Sort Strings using localeCompare() or non-ASCII characters.
Code:
let employee_Ascii = ['nèha', 'hardik', 'éaster', 'chaitanya', 'spain'];
employee_Ascii.sort(function (str1, str2) {
return str1.localeCompare(str2);
});
console.log('Here is the Employee names in ascending order using ASCII code', employee_Ascii)
Output:
Here we use the localeCompare() function with two arguments str1 and str2 which is used for non-ASCII characters.
When there is no compare function passed, all the non-undefined elements of the array are converted to strings first. These are then compared with UTF-16 code value and sorting is done in ascending order. Elements that are undefined are sorted or kept to the end of the array.
When there is a compare function passed, as shown above, all nonundefined elements of the array are sorted based on the return value of the compare function defined. All the undefined elements are sorted at the end of the array, with no call to the compare function on these elements.
Example #4
Sort string in JavaScript using ASCII code
Code:
let employee_Ascii = ['nèha', 'hardik', 'éaster', 'chaitanya', 'spain'];
employee_Ascii.sort(function (a, b) {
return a.localeCompare(b);
});
console.log('Here is the Employee names in ascending order using ASCII code', employee_Ascii);
Output:
So here the sorting of elements is done based on ASCII values of the input elements.
Example #5
Sort string in JavaScript in descending order
Code:
var employer = [
'wipro', 'yohima', 'accentur', 'capgemine', 'infosyss'
];
employer.sort(function (x, y) {
if (x > y) {
return -1;
}
if (y > x) {
return 1;
}
return 0;
});
console.log("Here are the employers in descending order", employer);
Output:
Here are the sorted values in descending order, it is purely based on the compare function declared.
With this, we conclude the topic ‘Sort string in JavaScript’. We have seen what Sort string means, its syntax and how is it used. Seen various ways of sorting strings in JavaScript, one using the sort() method and the other using the loop over the array elements, which is actually similar to the localeCompare function seen in the above examples. In this part of JavaScript, we have learned about how to go for sorting strings in alphabetical order. The examples shown above have almost all the concepts covered here, a simple sort, descending sort, sorting on integers, using a compare function, and the rest. Thanks! Happy Learning!!
Recommended Articles
This is a guide to Sort string in JavaScript. Here we discuss How to sort strings in JavaScript using various ways along with the Examples and outputs. You may also have a look at the following articles to learn more –