Finding shortest word in a string in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
raja
Published on 10-Oct-2020 11:52:58
Advertisements