- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 Smallest element from a string array in 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.
Therefore, let’s write the code for this function −
Example
The code for this will be −
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
The output in the console will be −
be
- Related Articles
- C# Program to find the smallest element from an array
- C# Program to find the smallest element from an array using Lambda Expressions
- Swift Program to Find Smallest Array Element
- Get the smallest array from an array of arrays in JavaScript
- Finding smallest element in a sorted array which is rotated in JavaScript
- Nth smallest element in sorted 2-D array in JavaScript
- C# program to find K’th smallest element in a 2D array
- Python program to find k'th smallest element in a 2D array
- Building an array from a string in JavaScript
- Function to find the length of the second smallest word in a string in JavaScript
- JavaScript Splitting string by given array element
- Find the smallest number in a Java array.
- Remove element from array referencing spreaded array in JavaScript
- Largest and smallest word in a string - JavaScript
- Finding second smallest word in a string - JavaScript

Advertisements