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

JavascriptWeb DevelopmentFront End Technology

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 −

 Live Demo

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
raja
Published on 20-Apr-2021 09:27:37
Advertisements