

- 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
Finding shortest word in a string in JavaScript
We are required to write a JavaScript function that takes in a string and returns the shortest word from the string.
For example: If the input string is −
const str = 'This is a sample string';
Then the output should be −
const output = 'a';
Example
The code for this will be −
const str = 'This is a sample string'; const findSmallest = str => { const strArr = str.split(' '); const creds = strArr.reduce((acc, val) => { let { length, word } = acc; if(val.length < length){ length = val.length; word = val; }; return { length, word }; }, { length: Infinity, word: '' }); return creds.word; }; console.log(findSmallest(str));
Output
The output in the console −
a
- Related Questions & Answers
- Finding second smallest word in a string - JavaScript
- Finding the longest word in a string in JavaScript
- Shortest Completing Word in Python
- Finding all valid word squares in JavaScript
- Shortest Word Distance II in C++
- Shortest Word Distance III in C++
- Finding mistakes in a string - JavaScript
- Corresponding shortest distance in string in JavaScript
- Finding word starting with specific letter in JavaScript
- Finding average word length of sentences - JavaScript
- Word Ladder (Length of shortest chain to reach a target word) in C++
- Finding missing letter in a string - JavaScript
- Largest and smallest word in a string - JavaScript
- Twice repetitive word count in a string - JavaScript
- Finding hamming distance in a string in JavaScript
Advertisements