JavaScript - Sort an Array of Strings
Last Updated :
03 Dec, 2024
Here are the various methods to sort an array of strings in JavaScript
1. Using Array.sort() Method
The sort() method is the most widely used method in JavaScript to sort arrays. By default, it sorts the strings in lexicographical (dictionary) order based on Unicode values.
JavaScript
let a = ['Banana', 'Apple', 'Cherry', 'Mango'];
a.sort();
console.log(a);
Output[ 'Apple', 'Banana', 'Cherry', 'Mango' ]
- sort() sorts the array a in place. In the case of strings, it compares the Unicode values of the characters.
- This method sorts the strings in ascending order by default.
2. Using Array.sort() with a Custom Comparator
If you need more control over the sorting (e.g., sorting case-insensitively or in reverse order), you can pass a custom comparator function to the sort() method.
Case-Insensitive Sort
JavaScript
let a = ['banana', 'Apple', 'cherry', 'Mango'];
a.sort((s1, s2) =>
s1.toLowerCase().localeCompare(s2.toLowerCase()));
console.log(a);
Output[ 'Apple', 'banana', 'cherry', 'Mango' ]
- localeCompare() compares two strings and returns a negative, zero, or positive value based on their lexicographical order.
- By using toLowerCase(), you ensure the sorting is case-insensitive.
Reverse Order Sort
JavaScript
let a = ['Banana', 'Apple', 'Cherry', 'Mango'];
a.sort((s1, s2) =>
s2.localeCompare(s1));
console.log(a);
- The comparator function (s1, s2) => s2.localeCompare(s1) reverses the order of comparison, resulting in descending order.
3. Using Array.sort() with Numeric Sorting (for Length)
If you need to sort an array of strings by the length of each string (instead of lexicographically), you can customize the comparator to compare string lengths.
JavaScript
let a = ['Banana', 'Apple', 'Cherry', 'Mango'];
a.sort((s1, s2) =>
s1.length - s2.length);
console.log(a);
Output[ 'Apple', 'Mango', 'Banana', 'Cherry' ]
- The comparator function (s1, s2) => s1.length - s2.length sorts the strings by their length in ascending order.
- You can modify the comparator to sort in descending order by changing the comparison to s2.length - s1.length.
4. Using Array.sort() with Locale-Sensitive Sorting
If you're working with strings in different languages and need to account for locale-specific sorting rules (e.g., accented characters), you can use localeCompare() with the locales and options parameters.
JavaScript
let a = ['apple', 'banana', 'cherry', 'mango', 'ápple'];
a.sort((s1, s2) =>
s1.localeCompare(s2, 'en', { sensitivity: 'base' }));
console.log(a);
Output[ 'apple', 'ápple', 'banana', 'cherry', 'mango' ]
- localeCompare() with en as the locale ensures that sorting respects the English alphabet's rules.
- The sensitivity: 'base' option ignores diacritic marks (e.g., accents).
5. Using Array.sort() with Custom Order (Non-Alphabetical)
If you want to sort the strings based on a custom order (not just alphabetically), you can define an order map and sort the array based on this custom order.
JavaScript
let a = ['Banana', 'Apple', 'Mango', 'Cherry'];
let order = ['Mango', 'Apple', 'Banana', 'Cherry']; //custom order
a.sort((s1, s2) =>
order.indexOf(s1) - order.indexOf(s2));
console.log(a);
Output[ 'Mango', 'Apple', 'Banana', 'Cherry' ]
- The order.indexOf(s1) and order.indexOf(s2) functions retrieve the indices of each string in the custom order array, sorting the array based on these indices.
Which Approach to Choose?
Method | When to Use | Why Choose It |
---|
sort() Method | For simple alphabetical sorting. | Default and efficient for most cases, with lexicographical sorting. |
Custom Comparator with sort() | When you need case-insensitive or reverse order sorting. | Provides full control over how strings are compared and ordered. |
sort() with Length Sorting | When sorting by string length. | Useful when you need to prioritize short or long strings. |
localeCompare() for Locale-Sensitive Sorting | When dealing with internationalization and accented characters. | Ensures correct sorting for different languages and special characters. |
Custom Order Sorting | When you need a custom sorting order. | Great for non-alphabetical sorting based on predefined rules. |
Similar Reads
How to Get Character of Specific Position using JavaScript ? Get the Character of a Specific Position Using JavaScript We have different approaches, In this article we are going to learn how to Get the Character of a Specific Position using JavaScript Below are the methods to get the character at a specific position using JavaScript: Table of Content Method 1
4 min read
Remove a Character From String in JavaScript In JavaScript, a string is a group of characters. Strings are commonly used to store and manipulate text data in JavaScript programs, and removing certain characters is often needed for tasks like:Removing unwanted symbols or spaces.Keeping only the necessary characters.Formatting the text.Methods t
3 min read
Reverse a String in JavaScript We have given an input string and the task is to reverse the input string in JavaScript. Reverse a String in JavaScriptUsing split(), reverse() and join() MethodsThe split() method divides the string into an array of characters, reverse() reverses the array, and join() combines the reversed characte
1 min read
JavaScript - Convert String to Title Case Converting a string to title case means capitalizing the first letter of each word while keeping the remaining letters in lowercase. Here are different ways to convert string to title case in JavaScript.1. Using for LoopJavaScript for loop is used to iterate over the arguments of the function, and t
4 min read
JavaScript - Sort an Array of Strings Here are the various methods to sort an array of strings in JavaScript1. Using Array.sort() MethodThe sort() method is the most widely used method in JavaScript to sort arrays. By default, it sorts the strings in lexicographical (dictionary) order based on Unicode values.JavaScriptlet a = ['Banana',
3 min read
How to Convert String to Camel Case in JavaScript? We will be given a string and we have to convert it into the camel case. In this case, the first character of the string is converted into lowercase, and other characters after space will be converted into uppercase characters. These camel case strings are used in creating a variable that has meanin
4 min read
Extract a Number from a String using JavaScript We will extract the numbers if they exist in a given string. We will have a string and we need to print the numbers that are present in the given string in the console.Below are the methods to extract a number from string using JavaScript:Table of ContentUsing JavaScript match method with regExUsing
4 min read
JavaScript - Delete First Character of a String To delete the first character of a string in JavaScript, you can use several methods. Here are some of the most common onesUsing slice()The slice() method is frequently used to remove the first character by returning a new string from index 1 to the end.JavaScriptlet s1 = "GeeksforGeeks"; let s2 = s
1 min read
JavaScript - How to Get Character Array from String? Here are the various methods to get character array from a string in JavaScript.1. Using String split() MethodThe split() Method is used to split the given string into an array of strings by separating it into substrings using a specified separator provided in the argument. JavaScriptlet s = "Geeksf
2 min read
JavaScript - How To Get The Last Caracter of a String? Here are the various approaches to get the last character of a String using JavaScript.1. Using charAt() Method (Most Common)The charAt() method retrieves the character at a specified index in a string. To get the last character, you pass the index str.length - 1.JavaScriptconst s = "JavaScript"; co
3 min read