Sort an array of Strings in JavaScript ?
In this article, we will sort an array of strings in Javascript. we will be given an array having strings as elements we need to sort them according to the series of A-Z.
We can sort the strings in JavaScript by the following methods described below:
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.
Example: In this example, we will sort the elements of an array using the Javascript sort() method.
javascript
let string = [ 'Suraj' , 'Sanjeev' , 'Rajnish' , 'Yash' , 'Ravi' ]
console.log( 'Original String' )
console.log(string)
string.sort()
console.log( 'After sorting' )
console.log(string)
|
Output
Original String
[ 'Suraj', 'Sanjeev', 'Rajnish', 'Yash', 'Ravi' ]
After sorting
[ 'Rajnish', 'Ravi', 'Sanjeev', 'Suraj', 'Yash' ]
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.
Example: In this example, we will be using the Javascript loop to sort the elements of an array.
javascript
function string_sort (str) {
let i = 0,
j
while (i < str.length) {
j = i + 1
while (j < str.length) {
if (str[j] < str[i]) {
let temp = str[i]
str[i] = str[j]
str[j] = temp
}
j++
}
i++
}
}
let string = [ 'Suraj' , 'Sanjeev' , 'Rajnish' , 'Yash' , 'Ravi' ]
console.log( 'Original String' )
console.log(string)
string_sort(string)
console.log( 'After sorting' )
console.log(string)
|
Output
Original String
[ 'Suraj', 'Sanjeev', 'Rajnish', 'Yash', 'Ravi' ]
After sorting
[ 'Rajnish', 'Ravi', 'Sanjeev', 'Suraj', 'Yash' ]
This approach creates a shallow copy of the array using the spread operator (...
) and then applies the sort()
method. It ensures that the original array remains unchanged while obtaining a sorted version.
Example:
In this example, we are using
Using the spread operator (...
) and sort().
Javascript
const array3 = [ 'banana' , 'apple' , 'orange' , 'grape' ];
const sortedArray3 = [...array3].sort();
console.log(sortedArray3);
|
Output
[ 'apple', 'banana', 'grape', 'orange' ]
Last Updated :
29 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...