Sorting words by last character present in them in JavaScript


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

Updated on: 19-Apr-2021

371 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements