- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Sorting string of words based on the number present in each word using JavaScript
- Reversing words present in a string in JavaScript
- If string includes words in array, remove them JavaScript
- Sorting an array including the elements present in the subarrays in JavaScript
- Sorting an array by date in JavaScript
- Sorting arrays by two criteria in JavaScript
- Sorting an array by price in JavaScript
- Sorting string characters by frequency in JavaScript
- JavaScript array sorting by level
- How to ORDER BY last 2 character string in MySQL?
- Sorting objects by numeric values - JavaScript
- How to replace characters except last with a mask character in JavaScript?
- Create palindrome by changing each character to neighboring character in JavaScript
- MySQL query to sort by certain last string character?
- Sorting one string by the order of second in JavaScript

Advertisements