问题
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