jdev99
jdev99

Reputation: 95

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?

Upvotes: 2

Views: 12042

Answers (3)

Th1
Th1

Reputation: 291

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'

Upvotes: 0

guijob
guijob

Reputation: 4488

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

Upvotes: 2

31piy
31piy

Reputation: 23859

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

Upvotes: 7

Related Questions