简体   繁体   中英

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

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 ?

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

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 

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' 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM