Sorting words by last character present in them in JavaScript


We are required to write a JavaScript function that takes in a string of words str. Our function needs to return an array of the words, sorted alphabetically by the final character in each.

If two words have the same last letter, the returned array should show them in the order they appeared in the given string.


Following is the code −

 Live Demo

const str = 'this is some sample string';
const sortByLast = (str = '') => {
   const arr = str.split(' ');
   const sorter = (a, b) => {  
      return a[a.length - 1].charCodeAt(0) - b[b.length - 1].charCodeAt(0);
   const sortedString = arr.join(' ');
   return sortedString;


Following is the console output −

some sample string this is