Find the Longest Word in a String without Split

I’m trying to only use techniques that have been taught so far in the curriculum. I’m attempting to create and array wordBank that stores the lengths of everyword in the string and then return the math.max from that array. I seem to be having some troble pushing the currentWord value onto the wordBank array. Can someone point out where I’m going wrong?

Your code so far

function findLongestWordLength(str) {
  let currentWord = 0;
  let wordBank=[];
  for (let i=0; i<str.length; i++){
    if (str[i] !== " "){
      currentWord++;
    }
    else{
      wordBank.push(currentWord);
      currentWord=0;
    } 
  }
  return(Math.max(wordBank));
}

console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36

Challenge: {{challengeTitle}} Basic Algorithm Scripting - Find the Longest Word in a String

Link to the challenge:

Read the documentation on Math.max. It even has an example of how to use it with an array.

1 Like

Thank you so much bbsmooth for pointing me in the right direction! if anyone else happens to stumble upon this post note that even with the Math.max fix the wordBank array isn’t logging the last word in the sentence without a fix.

You can fix that simply by putting another wordBank.push(currentWord); after the loop above the return statement, which will push the last accumulated value of currentWord into wordBank

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.