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 returns legend[1] which is 1
  • When a is false, it returns legend[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.

Updated on: 2026-03-15T23:19:00+05:30

362 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements