How to use the sort() method In Javascript
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 code to sort strings
// Original string
let 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)
Output
Original String [ 'Suraj', 'Sanjeev', 'Rajnish', 'Yash', 'Ravi' ] After sorting [ 'Rajnish', 'Ravi', 'Sanjeev', 'Suraj', 'Yash' ]
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:
Table of Content
- Method 1: Using the sort() method
- Method 2: Using JavaScript Loops
- Method 3: Using the spread operator (…) and sort() method
- Method 4: Using the localeCompare() Method