Computer >> Computer tutorials >  >> Programming >> Javascript

Sorting alphabets within a string in JavaScript


Suppose, we have a comma separated string of words like this −

const str = 'JAY, ROB';

We are required to write a JavaScript function that takes in one such string. The function could create a new word from the words in the string where the preceding alphabet is always greater than equal to the next (for e.g. A is greater than B)

For example, in the above string we want to compare the first letter of JAY with the first letter of ROB.

Since J comes first when compared with R, the first alphabet of the new word will be J. Comparing the second, since A comes before R it becomes the second alphabet, the third alphabet similarly becomes R.

Therefore, the final word would be 'JAROBY',

Note that, for this very example, we took a string with only two words, but we are required to write a solution that can work with more than two words as well.

Example

The code for this will be −

const str = `JAY,ROB,APPLE,AAKO`;
const specialSort = (str = '') => {
   let len = str.replace(/,/g, "").length;
   const sorter = (str, b) => {
      if(str === "" || str === null) return 1;
      if(b === "" || b === null) return −1;
      if(str === b) return 0;
      return str < b ? −1 : 1;
   };
   let res = "";
   let sorted = str.split(",").sort(sorter);
   while (res.length < len){
      res += sorted[0][0];
      sorted[0] = sorted[0].slice(1);
      sorted = sorted.sort(sorter);
   }
   return res;
};
console.log(specialSort(str));

Output

And the output in the console will be −

AAAJAKOPPLEROBY