Basic Algorithm Scripting - Find the Longest Word in a String; stuck in a rut

Tell us what’s happening:
So I’ve tried several things so far. I still think my best bet would be to make an array and push the value of i into it and then iterate through that array to pick the highest number. I’m struggling trying to find a way to reset the count after the space. I can’t reset i to zero otherwise it will never get to the end of the string length. I guess I’m confusing myself over trying to figure out how to count the total characters per word. I just feel like I need advice and it’s hard to try and find it here without seeing code and it might potentially spoil a part of the problem I haven’t figured out yet. Advice is appreciated.

Your code so far

function findLongestWordLength(str) {
  let letterCount;
  let space = 0;
  for (let i = 0; i < str.length; i++) {
    letterCount = i;
    if (str[i] === " "){
      space++;
      //console.log(space);
    }
    
  }
  console.log(letterCount - space);
  }
 
    
      

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; rv:109.0) Gecko/20100101 Firefox/111.0

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

Link to the challenge:

Instead of setting counter to i would incrementing it be better?

2 Likes

Following your idea you could:

  • Increment letterCount
  • When you find a space you push the value to an array and reset letterCount to 0

Good luck! :grinning:

1 Like

Thanks I managed to do it after a bit and then I finished it. It was probably not as clean as it should be though.

Thanks I managed to complete it.

Cool… now that you’ve finished, other thoughts :). If you know words are separated by a space, have you seen the split function for strings?

let myArray = myString.split(" ")

That actual takes a string and splits it up into an array of strings, and you specify how you want to split it in the (), in this case, with a space. So you could split it, then go through each array item and look for the one with the longest length. The arrays reduce function would make short work of that too, altough reduce can be a little complex, so not a beginner thing.

Just in case you’re wondering about other ways to do it.

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