DEV Community

Discussion on: Algorithm 101: 6 Ways to Find the Longest Word in a Sentence

Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan • Edited

Here's the reduce version for those who are wondering:

function longestWord(sentence) {
    return sentence.split(" ").reduce((longestWord, currentWord) => {
        return currentWord.length > longestWord.length ? currentWord : longestWord;
    }, '');
}

Edited, to clarify how the code works:

  1. sentence.split(" ") returns an array of words.
  2. Since the previous step creates an array, we can call reduce on it.
  3. Reduce takes two arguments: the "accumulator" (in this case, the longest word) and the current element (currentWord).
  4. In each iteration of the callback, we return the longer of the two words.
  5. Reduce initially starts with the empty string, to guarantee that there's always something longer than it.
Collapse
 
ebereplenty profile image
NJOKU SAMSON EBERE

This is awesome, Aleksandr. Works perfectly. Can you walk us through the code?

Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

Sure, edited to clarify

Thread Thread
 
ebereplenty profile image
NJOKU SAMSON EBERE

Thank you for the explanation. You are good.