Javascript reduce() to find the shortest word in a string

孤者浪人 提交于 2021-02-07 04:18:02

问题


I have a function that finds the longest word in a string.

function findLongestWord(str) {
  var longest = str.split(' ').reduce((longestWord, currentWord) =>{
    return currentWord.length > longestWord.length ? currentWord : longestWord;
  }, "");
  return longest;
}
console.log(findLongestWord("The quick brown fox jumped over the lazy dog"));

I'm having a hard time converting this to find the shortest word. Why can't I just change currentWord.length > longestWord.length to currentWord.length < longestWord.length?


回答1:


You need to provide an initial value to the reduce function, otherwise a blank string is the shortest word:

function findShortestWord(str) {
  var words = str.split(' ');
  var shortest = words.reduce((shortestWord, currentWord) => {
    return currentWord.length < shortestWord.length ? currentWord : shortestWord;
  }, words[0]);
  return shortest;
}
console.log(findShortestWord("The quick brown fox jumped over the lazy dog"));



回答2:


While using reduce, initialValue is optional and if it isn't provided then your first element will be used as initialValue. So, in your case, you'll just have to remove your "":

function findLongestWord(str) {
  var longest = (typeof str == 'string'? str : '')
    .split(' ').reduce((longestWord, currentWord) =>{
      return currentWord.length < longestWord.length ? currentWord : longestWord;
  });
  return longest;
}
console.log(findLongestWord("The quick brown fox jumped over the lazy dog")); // The



回答3:


I coded it in this way

const findLongestWord = str => {
  return typeof str === 'string' 
  ? str.split(' ').reduce((sw, lw) => lw.length < sw.length ? lw :sw)
  : '';
}
console.log(findLongestWord('The quick brown fox jumps over the lazy dog.')); //'The'


来源:https://stackoverflow.com/questions/49124172/javascript-reduce-to-find-the-shortest-word-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!