Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Arranging words by their length in a sentence in JavaScript
In JavaScript, you can arrange words in a sentence by their length using string manipulation and array sorting methods. This technique is useful for text processing and formatting applications.
A sentence is a string of characters joined by whitespaces. The goal is to rearrange words so the shortest word appears first, followed by progressively longer ones.
Problem Example
If the input string is:
const str = 'this is a string';
Then the output should be:
const output = 'a is this string';
Solution Using Array Methods
Here's a complete solution that sorts words by length while preserving original order for words of equal length:
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));
a is this string
How It Works
The solution works in several steps:
- Convert to lowercase: Ensures consistent comparison
- Split into words: Creates an array of individual words
- Map with metadata: Creates objects containing the word, its length, and original index
- Sort by length: Primary sort by length, secondary sort by original position
- Reconstruct string: Joins the sorted words back into a sentence
Alternative Simplified Approach
For a more concise solution without preserving original order for equal-length words:
const arrangeWordsByLength = (sentence) => {
return sentence.toLowerCase()
.split(' ')
.sort((a, b) => a.length - b.length)
.join(' ');
};
const str = 'this is a string';
console.log(arrangeWordsByLength(str));
a is this string
Comparison of Methods
| Method | Preserves Order | Code Length | Performance |
|---|---|---|---|
| Object-based sorting | Yes | Longer | Slightly slower |
| Simple sort | No | Shorter | Faster |
Conclusion
Use the object-based approach when you need to preserve the original order of equal-length words. For simpler cases, the direct sorting method provides cleaner code with the same core functionality.
