Sorting string of words based on the number present in each word using JavaScript


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.


Following is the code −

 Live Demo

const str = "is2 Thi1s T4est 3a";
const sortByNumber = (str = '') => {
   const findNumber = (s = '') => s
      .reduce((acc, val) => +val ? +val : acc, 0);
   const arr = str.split(' ');
   const sorter = (a, b) => {
      return findNumber(a) - findNumber(b);
   return arr.join(' ');


Thi1s is2 3a T4est