Basic Algorithm Scripting - Find the Longest Word in a String - Omg I'm so close

Tell us what’s happening:
So I have spent a solid 20 minutes thinking this through and I really want to solve it without looking at the solution.

I get correct answers on this UNTIL i had the word “jumped…”

No idea whats happening. The answer I am getting for both function calls is 8

FOR CLARITY**

record is actually the highest number. I have since changed highCount to just count

When I use console.log(count) in the function, I get back that the function is seeing “brown fox” as an 8 letter word.

  **Your code so far**
function findLongestWordLength(str) {
let highCount = 0;
let record = 0;
for (let i = 0; i <= str.length - 1; i++) {
  if (str[i] !== " ") {
    highCount += 1;
  } 
  else if (str[i] === " " && highCount > record) {
    record = highCount;
    highCount = 0;
  } 
  else if (str[i] === " " && highCount < record) {
    highCount = 0;
  }
}
console.log(record);
return record;
}
//im going to be really proud when I figure this out

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

findLongestWordLength("May the force be with you")
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36

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

Link to the challenge:

I might try a slightly different approach on this. Was there a previous lesson that covered turning a string with space separated words into an array? Or perhaps just splitting up a string into an array based on some character?

But if you want to do it this way, then you check if highCount > record and if highCount < record, but what if highCount === record?

Fair enough! There was the split() function. Didn’t think about that and wasn’t sure how to approach the problem from there either.

Using split is going to be easier because you don’t have to manage the spaces in the string, split does it for you.

1 Like

And then use the loop to filter through the words and if a word is greater than the max length then set that word to the max length?

I think you might be on to something there :slight_smile:

and because you don’t check for the “equal” case (as bbsmooth noticed), your code would have “record” set to 5 after the word quick and then would have “high” count at 5 after “brown” but would not clear high count since it is not greater than or less than “record” (i.e. it is equal). So then high count would keep counting with “fox” and end up at 8 and then get stored as “record”.

Ahhhhhh that freaking did it. That made it work

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