Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 are required to write a function that returns the longest and the shortest word from this array. We will use Array.prototype.reduce() method to keep track of the longest and shortest word in the array through a complete iteration.
The code for this will be −
Example
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));
Output
The output in the console will be −
{ longest: 'sentence.', shortest: 'a' }Advertisements