 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Arranging words by their length in a sentence in JavaScript
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';
Example
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) }; console.log(arrangeWords(str));  Output
Following is the console output −
a is this string
Advertisements
 