
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 String of Words Based on Number in Each Word Using JavaScript
Problem
We are required to write a JavaScript function that takes in a string that represents a sentence. Our function should sort this sentence.
Each word in the sentence string contains an integer. Our function should sort the string such that the word that contains the smallest integer is placed first and then in the increasing order.
Example
Following is the code −
const str = "is2 Thi1s T4est 3a"; const sortByNumber = (str = '') => { const findNumber = (s = '') => s .split('') .reduce((acc, val) => +val ? +val : acc, 0); const arr = str.split(' '); const sorter = (a, b) => { return findNumber(a) - findNumber(b); }; arr.sort(sorter); return arr.join(' '); }; console.log(sortByNumber(str));
Output
Thi1s is2 3a T4est
Advertisements