- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
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
Advertisements