Sort an array of Strings in JavaScript ?
In this article, we will sort strings in Javascript. We can sort the strings in JavaScript by the following methods described below:
- Using sort() method
- Using loop in Javascript
Using sort() method: In this method, we use the predefined sort() method of JavaScript to sort the array of strings. This method is used only when the string is alphabetic. It will produce wrong results if we store numbers in an array and apply this method.
The below examples illustrate the above approach:
Example: In this example, we will sort the elements of an array using the Javascript sort() method.
javascript
<script> // JavaScript code to sort strings // Original string var string = [ "Suraj" , "Sanjeev" , "Rajnish" , "Yash" , "Ravi" ]; // Print original string array console.log( "Original String" ); console.log(string); // Use sort() method to sort the strings string.sort(); console.log( "After sorting" ); // Print sorted string array console.log(string); </script> |
Output:
Original String Suraj, Sanjeev, Rajnish, Yash, Ravi After sorting Rajnish, Ravi, Sanjeev, Suraj, Yash
Using loop: We will use a simple approach of sorting to sort the strings. In this method, we will use a loop and then compare each element and put the string at its correct position. Here we can store numbers in an array and apply this method to sort the array.
The below example illustrates the above approach:
Example: In this example, we will be using the Javascript loop to sort the elements of an array.
javascript
<script> // JavaScript code to sort the strings // Function to perform sort 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++; } } // Driver code // Original string var string = [ "Suraj" , "Sanjeev" , "Rajnish" , "Yash" , "Ravi" ]; // Print original string array console.log( "Original String" ); console.log(string); // Call string_sort method string_sort(string); console.log( "After sorting" ); // Print sorted string array console.log(string); </script> |
Output:
Original String Suraj, Sanjeev, Rajnish, Yash, Ravi After sorting Rajnish, Ravi, Sanjeev, Suraj, Yash
Please Login to comment...