Find the Longest Word in a String Help

Find the Longest Word in a String Help
0

#1

Tell us what’s happening:
Hello campers,
I tried to do this exercise a few times before ending up with this solution, and even though the console returns 5, for the phrase “May the force be with you” (which is correct), it keeps saying that its wrong.

Your code so far

var arraycompare = [];
function findLongestWord(str) {
  var array = str.split(" ");
  for (var i=0; array.length>i; i++){
   arraycompare.push(array[i].length);
    
  }
  var sortedarray= arraycompare.sort(function(a, b){
    return b-a;
   
  });
  var result = sortedarray[0];
  return result;
}


findLongestWord("May the force be with you");

Your browser information:

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

Link to the challenge:


#2

Even though you code is correct, you need to put var arraycompare = []; line inside the function. I don’t know why but it has to be there.


#3

It Worked ! Thanks for the Help!


#4

The reason why is because when the FCC tests runs your code, any variable declared globally (outside of the function that will tested) will continue to store the value it had at the completion of the previous test call.

So, in this particular challenge, after the first test, arraycompare would be:

[ 6, 5, 5, 4, 4, 3, 3, 3, 3 ]

and after the second test it would be:

[ 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 2 ]

after third test:

[ 6, 6, 6, 5, 5, 5, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 2, 2, 1 ]

and so on, because inside the for loop, arraycompare keeps growing (because of the push).