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' ]

Updated on: 15-Sep-2020

848 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements