Arranging Words in Ascending Order in a String - JavaScript



Let’s say, we are required to write a JavaScript function that takes in a string and returns a new string with words rearranged according to their increasing length.

Example

Following is the code −

const str = 'This is a sample string only';
const arrangeByLength = str => {
   const strArr = str.split(' ');
   const sorted = strArr.sort((a, b) => {
      return a.length - b.length;
   });
   return sorted.join(' ');
};
console.log(arrangeByLength(str));

Output

Following is the output in the console −

a is This only sample string
Updated on: 2020-09-18T09:49:28+05:30

364 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements