

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 the number present 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
- Related Questions & Answers
- Sorting words by last character present in them in JavaScript
- Reversing words present in a string in JavaScript
- Sorting Array based on another array JavaScript
- Order an array of words based on another array of words JavaScript
- Sorting array based on increasing frequency of elements in JavaScript
- Repeating each character number of times their one based index in a string using JavaScript
- Constructing a sentence based on array of words and punctuations using JavaScript
- Python Program to Calculate the Number of Words and the Number of Characters Present in a String
- How to capitalize the first letter of each word in a string using JavaScript?
- Finding the number of words in a string JavaScript
- Sorting numbers based on their digit sums in JavaScript
- Replace all occurrence of specific words in a sentence based on an array of words in JavaScript
- Encrypting a string based on an algorithm using JavaScript
- Break the line based on word with CSS
- Find the Number of Substrings of One String Present in Other using C++
Advertisements