How to use the localeCompare() Method In Javascript
The localeCompare() method compares two strings in the current locale, returning a number that indicates whether a reference string comes before or after or is the same as the given string in sort order. This method is particularly useful for sorting strings that may contain special characters or when sorting according to a specific locale is required.
Example: In this example, we will use the localeCompare() method to sort an array of strings.
// JavaScript code to sort strings using localeCompare()
// Original string array
let string = ['éclair', 'apple', 'banana', 'Éclair', 'grape'];
// Print original string array
console.log('Original String');
console.log(string);
// Use sort() method with localeCompare to sort the strings
string.sort((a, b) => a.localeCompare(b));
// Print sorted string array
console.log('After sorting');
console.log(string);
Output
Original String [ 'éclair', 'apple', 'banana', 'Éclair', 'grape' ] After sorting [ 'apple', 'banana', 'éclair', 'Éclair', 'grape' ]
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