Problem with Find the Longest Word in a String using .sort() *SOLVED*

Problem with Find the Longest Word in a String using .sort() *SOLVED*
0.0 0

#1

Hello fellow Campers!

I’m having a bit of a problem with the “Find the Longest Word in a String” challenge. The code below works as far as I can tell. I get a check mark for every criterion with the exception of “findLongestWord(“May the force be with you”) should return 5.” The problem is, when I pass that string in the console it does return 5. Is my code incorrect, or is this an error on the site itself? I’ve checked for typos, syntax errors, etc. and can’t find anything wrong. Does anyone else see where I’m messing up?

Thanks so much!

-Spencer

Your code so far


function findLongestWord(str) {
  var sentenceArr = str.split(" ");
  for (var i = 0; i < sentenceArr.length; i++) {
    wordLengths.push(sentenceArr[i].length);
  }
    wordLengths.sort(function(a,b) {
      return b - a;
    });
  return wordLengths[0];
}

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

Link to the challenge:


#2

Are you sure you have posted all of your code? You do not declare the array called wordLengths, so if this is all the code you have, you should be getting a reference error of wordlengths is not defined when you try to push elements into it on line 4 of your function.


#3

*** EDIT ***

for some reason, line 1 of my code didn’t pop up when I wrote the original post, so here it is, just to prevent confusion.

var wordLengths = [];

Thanks again!

-Spencer


#4

You need to move that into the function. If not, since wordLengths is declared globally, each consecutive test will change the value of wordLengths and start with whatever elements were in wordLengths from the previous test. If you were to add the following line before the return statement, you would see how large the array is when it gets to the last test. Use the browser’s console (Ctrl+Shft+I in Chrome) to see what is happening. The FCC console is limited in what it can show.

console.log(wordLengths);

By the time all the tests have completed, there are 58 elements in the array.


#5

That did it! Thank you so much!


#6

For anyone else that might see this post, randelldawson’s solution worked perfectly. After making wordLengths a local variable, I encountered no problems.

Happy Coding!