Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Reverse alphabetically sorted strings in JavaScript
We are required to write a JavaScript function that takes in a lowercase string and sorts it in the reverse alphabetical order i.e., 'z' should come before 'y', 'b' before 'a', and so on.
Example
If the input string is:
const str = "hello";
Then the output should be:
const output = "ollhe";
Using Custom Comparator Function
Here's how we can achieve reverse alphabetical sorting using a custom comparator:
const string = 'hello';
const sorter = (a, b) => {
const legend = [-1, 0, 1];
return legend[+(a {
const strArr = str.split("");
return strArr
.sort(sorter)
.join("");
};
console.log(reverseSort(string));
ollhe
How It Works
The custom sorter function uses a clever approach:
- When
a is true, it returnslegend[1]which is1 - When
a is false, it returnslegend[0]which is-1 - This effectively reverses the normal sorting order
Alternative Method: Simple Reverse Sort
A more straightforward approach using built-in reverse comparison:
const reverseAlphabetical = str => {
return str.split("")
.sort((a, b) => b.localeCompare(a))
.join("");
};
console.log(reverseAlphabetical("hello"));
console.log(reverseAlphabetical("javascript"));
ollhe vstricpaja
Comparison
| Method | Readability | Performance |
|---|---|---|
| Custom legend array | Complex | Fast |
| localeCompare() | Clear | Slightly slower |
Conclusion
Both methods effectively reverse alphabetical sorting. The localeCompare() approach is more readable, while the custom comparator offers slightly better performance for large strings.
Advertisements
