
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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' }
- Related Articles
- Find the shortest string in an array - JavaScript
- Finding the longest string in an array in JavaScript
- Find longest string in array (excluding spaces) JavaScript
- How to get the length of longest string in a PHP array
- Finding all the longest strings from an array in JavaScript
- Corresponding shortest distance in string in JavaScript
- Which is the longest day and shortest night in the southern hemisphere?
- Length of shortest unsorted array in JavaScript
- Finding shortest word in a string in JavaScript
- Get the first and last item in an array using JavaScript?
- Search from an array of objects via array of string to get array of objects in JavaScript
- Finding the longest word in a string in JavaScript
- Length of longest string chain in JavaScript
- Get the smallest array from an array of arrays in JavaScript
- Finding the longest substring uncommon in array in JavaScript

Advertisements