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

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

#1

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


#2

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.


#3

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


#4

My only comment is to make sure and properly indent it, so it is more readable.

We are not going to post full code solutions of different ways to solve this problem. You are free to search the forum or look at the Get a Hint for the challenge and compare your solution to others.


#5

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


#6

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