Find the Longest Word in a String*

Tell us what’s happening:
All tests pass except this one
findLongestWordLength(“Google do a barrel roll”)
I can’t figure out why, thank you.

Your code so far


function findLongestWordLength(str) {
  let strArr = str.split(" ");
  let lengthArr = [];
  lengthArr[0] = strArr[0].length;
  //console.log(lengthArr);
  //console.log(strArr);
  for (let i= 1; i< strArr.length; i++) {
    if (strArr[i].length > lengthArr[0]) {
      lengthArr[0] = strArr[i].length;
      str = strArr[i];
    }
  }
  //console.log(lengthArr[0]);
  //console.log(str);
  //console.log(str.length);
  return str.length;
}

//findLongestWordLength("The quick brown fox jumped over the lazy dog");
findLongestWordLength("Google do a barrel roll");

Your browser information:

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

Link to the challenge:

  1. Create array from string by splitting. You already did that.
  2. Create an empty array that will be used for holding length values of every individual string from previously mentioned string array.
  3. Create loop that goes through string array and pushes length of every individual string into length array.
  4. After loop, sort length array using .sort(). Since sort is only good with string and not with numbers and since length array holds them(lengths of strings are number ofc.), as a parameter to sort() you should use compare function(google it.) in descending order.
  5. Return first member of length array.
1 Like

Hi
replace return str.length; by return lengthArr[0];

1 Like

Thank you for your answer,

My first code was exactly following those steps, except that I stopped in the third one and I got stuck, I didn’t know about the sort() and compare function. So I tried this new algorithm, wich succeeded except for that particular example, and I don’t see any reason why.

@OJL it worked, but when I took off the console.logs, Idw why they were blocking it.

Hi
So it didn’t work only for this case

"Google do a barrel roll"

because Google is the longest word, your for loop begin the iteration from index 1, so it didn’t find any word long than Google, so it didn’t access the if statement block and ending by returning 23 which is str.length

1 Like

Apart misunderstanding me, this algorithm works.

Didn’t catch that. Either way alg works. Just change what ousamma said and use alg.

1 Like