
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Questions & Answers
- Sorting the numbers from within in JavaScript
- Reversing alphabets in a string using JavaScript
- Converting a string to NATO phonetic alphabets in JavaScript
- Reversing words within a string JavaScript
- Performing shifts within a string in JavaScript
- Sorting string in reverse order in JavaScript
- Sorting a String in C#
- Sorting string characters by frequency in JavaScript
- Padding a string with random lowercase alphabets to fill length in JavaScript
- Adding paragraph tag to substrings within a string in JavaScript
- Counting all possible palindromic subsequence within a string in JavaScript
- Number to alphabets in JavaScript
- Sorting string alphabetically and inserting underscores using JavaScript
- Sorting a JSON object in JavaScript
- Indexing numbers to alphabets in JavaScript