Decreasing order sort of alphabets in JavaScript


Problem

We are required to write a JavaScript function that takes in a lowercase English alphabets string, str, as the first and the only argument

Our function should create and return a new string based on the input string which contains characters sorted according to the reverse English alphabets.

For example, if the input to the function is −

const str = 'abcdef';

Then the output should be −

const output = 'fedcba';

Example

Following is the code −

 Live Demo

const str = 'abcdef';
const reverseSorting = (str = '') => {
   const strArr = str.split('');
   const mapString = 'abcdefghijkmnopqrstuvwxyz';
   const sorter = (a, b) => {
      return mapString.indexOf(b) - mapString.indexOf(a);
   };
   strArr.sort(sorter);
   return strArr.join('');
};
console.log(reverseSorting(str));

Output

Following is the console output −

fedcba

Updated on: 21-Apr-2021

92 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements