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
Largest and smallest word in a string - JavaScript
We need to write a JavaScript function that takes a string and returns an array containing the smallest and largest words from the string based on their length.
For example, if we have the string:
const str = "Hardships often prepare ordinary people for an extraordinary destiny";
The output should be:
const output = ["an", "extraordinary"];
The word "an" has 2 characters (smallest) and "extraordinary" has 13 characters (largest).
Example
Here's the complete implementation:
const str = "Hardships often prepare ordinary people for an extraordinary destiny";
const largestSmallest = str => {
const strArr = str.split(" ");
let min = strArr[0];
let max = strArr[0];
for(let i = 1; i max.length){
max = strArr[i];
}
}
return [min, max];
};
console.log(largestSmallest(str));
[ 'an', 'extraordinary' ]
How It Works
The function follows these steps:
-
Split the string:
str.split(" ")converts the string into an array of words -
Initialize variables: Set both
minandmaxto the first word -
Compare lengths: Loop through remaining words and update
minandmaxbased on word length - Return result: Return an array with the smallest and largest words
Alternative Approach Using reduce()
Here's a more functional programming approach:
const str = "Hardships often prepare ordinary people for an extraordinary destiny";
const largestSmallestReduce = str => {
const words = str.split(" ");
return words.reduce((result, word) => {
if (word.length result[1].length) result[1] = word;
return result;
}, [words[0], words[0]]);
};
console.log(largestSmallestReduce(str));
[ 'an', 'extraordinary' ]
Edge Cases
The function handles various scenarios:
// Single word
console.log(largestSmallest("Hello"));
// Multiple words with same length
console.log(largestSmallest("cat dog fox"));
// Empty string handling
const handleEmpty = str => {
if (!str.trim()) return ["", ""];
return largestSmallest(str);
};
console.log(handleEmpty("JavaScript is awesome"));
[ 'Hello', 'Hello' ] [ 'cat', 'cat' ] [ 'is', 'JavaScript' ]
Conclusion
This function efficiently finds the smallest and largest words by splitting the string and comparing word lengths. Both the loop-based and functional approaches work well, with the choice depending on your coding style preference.
Advertisements
