How to usethe localeCompare() method in Javascript
The localeCompare()
the method compares two strings and returns a number indicating their relative order. We can use the localeCompare()
the method as a custom sorting function in conjunction with the sort()
method.
Syntax:
const sortedWords = wordsArray.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' }));
Example: In this example, we will see the use of the localeCompare() Method.
const words = [
"JavaScript",
"Program",
"to",
"Sort",
"Words",
"in",
"Alphabetical",
"Order",
];
// Sorting array using localeCompare
const sortedWords = words.sort((a, b) =>
a.localeCompare(b, undefined, { sensitivity: "base" })
);
// Show the sorted array output
console.log(sortedWords);
Output
[ 'Alphabetical', 'in', 'JavaScript', 'Order', 'Program', 'Sort', 'to', 'Words' ]
JavaScript Program to Sort Words in Alphabetical Order
Sorting words in alphabetical order involves arranging them based on the standard sequence of letters in the alphabet. This process helps in organizing data, making searches efficient, and presenting information in a clear and systematic manner.