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

Updated on: 10-Oct-2020

562 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements