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
Get the longest and shortest string in an array JavaScript
We have an array of string literals like this:
const arr = ['Some', 'random', 'words', 'that', 'actually', 'form', 'a', 'sentence.'];
We need to write a function that returns the longest and shortest word from this array. We will use the Array.prototype.reduce() method to keep track of the longest and shortest word during iteration.
Using Array.reduce() Method
The reduce() method processes each element and maintains an accumulator object containing both the longest and shortest strings found so far:
const arr = ['Some', 'random', 'words', 'that', 'actually', 'form', 'a', 'sentence.'];
const findWords = (arr) => {
return arr.reduce((acc, val) => {
const { length: len } = val;
if (len > acc['longest']['length']) {
acc['longest'] = val;
} else if (len < acc['shortest']['length']) {
acc['shortest'] = val;
}
return acc;
}, {
longest: arr[0],
shortest: arr[0]
});
};
console.log(findWords(arr));
{ longest: 'sentence.', shortest: 'a' }
How It Works
The function initializes both longest and shortest with the first array element. For each subsequent element, it compares lengths and updates the accumulator accordingly. The destructuring { length: len } = val extracts the string length for cleaner comparisons.
Alternative Approach Using Math Functions
You can also use Math.max() and Math.min() with find() for a more functional approach:
const arr = ['Some', 'random', 'words', 'that', 'actually', 'form', 'a', 'sentence.'];
const findWordsAlt = (arr) => {
const lengths = arr.map(str => str.length);
const maxLen = Math.max(...lengths);
const minLen = Math.min(...lengths);
return {
longest: arr.find(str => str.length === maxLen),
shortest: arr.find(str => str.length === minLen)
};
};
console.log(findWordsAlt(arr));
{ longest: 'sentence.', shortest: 'a' }
Comparison
| Method | Performance | Readability |
|---|---|---|
| reduce() | Better - single pass | Moderate |
| Math + find() | Slower - multiple passes | Higher |
Conclusion
The reduce() method provides the most efficient solution with a single array traversal. Choose the Math approach if code readability is prioritized over performance.
