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
Largest and smallest word in a string - JavaScript
We are required to write a JavaScript function that takes in string and returns an array with two string values, and they should be the smallest and largest words respectively from the string.
For example −
If the string is −
const str = "Hardships often prepare ordinary people for an extraordinary destiny";
Then the output should be −
const output = ["an", "extraordinary"];
So, let's write the code for this function
Example
Following is the code −
const str = "Hardships often prepare ordinary people for an extraordinary
destiny";
const largestSmallest = str => {
const strArr = str.split(" ");
let min = strArr[0];
let max = strArr[0];
for(let i = 1; i < strArr.length; i++){
if(strArr[i].length < min.length){
min = strArr[i];
};
if(strArr[i].length > max.length){
max = strArr[i];
};
};
return [min, max];
};
console.log(largestSmallest(str));
Output
The output in the console: −
[ 'an', 'extraordinary' ]
Advertisements