
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 Length of Second Smallest Word in a String using JavaScript
We are required to write a JavaScript function that takes in a string sentence as first and the only argument. And the function should return the length of the second smallest word from the string.
For example: If the string is −
const str = 'This is a sample string';
Then the output should be 2.
Therefore, let’s write the code for this function −
Example
The code for this will be −
const str = 'This is a sample string'; const secondSmallest = str => { const strArr = str.split(' '); if(strArr.length < 2){ return false; } for(let i = 0; i < strArr.length; i++){ strArr[i] = strArr[i].length; }; strArr.sort((a, b) => a - b); return strArr[1]; }; console.log(secondSmallest(str));
Output
The output in the console will be −
2
Advertisements