- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 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 −
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
Advertisements