"Find the Longest Word in a String" challenge best practice

hey guys ,
I’ve written this code down there and it worked in first shot . But I was like it can’t be a good way and there should be a better way . do you have any idea about the performance of different solutions ?

Your code so far


function findLongestWordLength(str) {
  let spacesIndex = [];
  for (let i in str) {
    if (str[i] == " ") {
      spacesIndex.push(i);
    }
  }
  spacesIndex.push(str.length)
  console.log(spacesIndex,spacesIndex.length)
  let SIclone = [...spacesIndex];
  for (let j =1; j < SIclone.length ; j++){
  SIclone[j] = spacesIndex[j] - spacesIndex[j-1]-1;
    
  }
  let ans = Math.max(...SIclone);
  return ans
}
  

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/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string

thanks , I added this tags :slight_smile:
hope other campers can see it after knowing that there’s a spoiler down in code

Interesting approach you went for here, finding all the spaces and then finding the maximum distance between them

You might want to revisit this question after the section on functional programming, this can be solved in a cute one-liner using a map

2 Likes

this approach has so many bugs! using more than one space , numbers and !?/)( in text string can give us a wrong answer!
thank you for the answer I’ll read other solutions