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
Selected Reading
Finding shortest word in a string in JavaScript
We are required to write a JavaScript function that takes in a string and returns the shortest word from the string.
For example: If the input string is:
const str = 'This is a sample string';
Then the output should be:
'a'
Using Array.reduce() Method
This approach splits the string into words and uses reduce() to find the shortest word by comparing lengths:
const str = 'This is a sample string';
const findSmallest = str => {
const strArr = str.split(' ');
const creds = strArr.reduce((acc, val) => {
let { length, word } = acc;
if(val.length < length){
length = val.length;
word = val;
};
return { length, word };
}, {
length: Infinity,
word: ''
});
return creds.word;
};
console.log(findSmallest(str));
a
Using Array.sort() Method
A simpler approach is to split the string and sort by length, then return the first element:
const str = 'This is a sample string';
const findShortestWord = str => {
return str.split(' ').sort((a, b) => a.length - b.length)[0];
};
console.log(findShortestWord(str));
a
Using for Loop Method
A traditional approach using a for loop to iterate through words:
const str = 'This is a sample string';
const findShortestWithLoop = str => {
const words = str.split(' ');
let shortest = words[0];
for (let i = 1; i < words.length; i++) {
if (words[i].length < shortest.length) {
shortest = words[i];
}
}
return shortest;
};
console.log(findShortestWithLoop(str));
a
Comparison
| Method | Performance | Readability | Best For |
|---|---|---|---|
Array.reduce() |
Good | Complex | Functional programming |
Array.sort() |
Slower | High | Simple solution |
for loop |
Best | Medium | Large datasets |
Conclusion
All three methods effectively find the shortest word. Use sort() for simplicity, for loop for performance, or reduce() for functional programming style.
Advertisements
