Sorting words by last character present in them in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

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.

Example

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);
   };
   arr.sort(sorter);
   const sortedString = arr.join(' ');
   return sortedString;
};
console.log(sortByLast(str));

Output

Following is the console output −

some sample string this is
raja
Published on 19-Apr-2021 08:07:32
Advertisements