在 JavaScript 中尋找字串中的最短單詞


我們需要編寫一個 JavaScript 函式,該函式接收一個字串並返回該字串中的最短單詞。

例如:如果輸入字串為 −

const str = 'This is a sample string';

則輸出應為 −

const output = 'a';

示例

此程式碼為 −

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));

輸出

控制檯中的輸出 −

a

更新日期:10-10-2020

660 閱讀

開啟您的 職業生涯

完成課程並獲得認證

開始
廣告