

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Find the shortest string in an array - JavaScript
We are required to write a JavaScript function that takes in an array of strings and returns the index of string that is shortest in length.
We will simply use a for loop and persist the index of string which is shortest in length.
Example
Following is the code −
const arr = ['this', 'can', 'be', 'some', 'random', 'sentence']; const findSmallest = arr => { const creds = arr.reduce((acc, val, index) => { let { ind, len } = acc; if(val.length < len){ len = val.length; ind = index; }; return { ind, len }; }, { ind: -1, len: Infinity }); return arr[creds['ind']]; }; console.log(findSmallest(arr));
Output
This will produce the following output in console −
be
- Related Questions & Answers
- Get the longest and shortest string in an array JavaScript
- Corresponding shortest distance in string in JavaScript
- Length of shortest unsorted array in JavaScript
- Finding shortest word in a string in JavaScript
- Find the Shortest Superstring in C++
- Find unique and biggest string values from an array in JavaScript
- Finding the longest string in an array in JavaScript
- Converting string to an array in JavaScript
- Find the closest value of an array in JavaScript
- Find the least duplicate items in an array JavaScript
- Find the Smallest element from a string array in JavaScript
- Finding the only unique string in an array using JavaScript
- Ordering string in an array according to a number in the string JavaScript
- Finding unique string in an array in JavaScript
- Find longest string in array (excluding spaces) JavaScript
Advertisements