Decreasing order sort of alphabets in JavaScript

JavascriptWeb DevelopmentFront End Technology

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
raja
Updated on 21-Apr-2021 11:56:19

Advertisements