Arranging words by their length in a sentence in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in a sentence as the first and the only argument.

A sentence is a special kind of string of characters joined by finite number of whitespaces.

The function should rearrange the words of the sentence such that the smallest word (word with least characters) appears first and then followed by bigger ones.

For example −

If the input string is −

const str = 'this is a string';

Then the output should be −

const output = 'a is this string';


Following is the code −

const str = 'this is a string';
const arrangeWords = (str = []) => {
   const data = str.toLowerCase().split(' ').map((val, i)=> {
      return {
         str: val,
         length: val.length,
         index: i
   data.sort((a,b) => {
      if (a.length === b.length)
         return (a.index - b.index)
      return (a.length - b.length)
   let res = '';
   let i = 0;
   while (i < data.length - 1)
      res += (data[i++].str + ' ');
   res += data[i].str;
   return (res)


Following is the console output −

a is this string
Updated on 19-Jan-2021 06:12:28