Find the Longest Word in a String (my take, your opinions)

So I started this challenge and decided to tackle it with an unusual method (I think :stuck_out_tongue_closed_eyes:). I splitted string into an array, forced it to be lowercase and sorted it.

If I’m correct I will be able to sort it by the length of each part of the array (the longest word will be the first element in this array) and then simply return a length value of the first element.

In order to do so I’m trying to deploy “function(a, b) {return b.length - a.length}” but with no luck :wink:

Am I correct in my thinking or am grasping at straws?

You should look up how the compare function to Array.prototype.sort() works. Keep in mind that particular problem expects a number in return. It looks as though you are sorting an array of words (ie strings) and might be returning the longest string, and not the number representing the length of that string.

Edit:

and then simply return a length value of the first element.

Sorry. I didn’t read this close enough.

1 Like

So I did it. After hours of failed attempts and tinkering with overly complex functions I verified my code with FCC article on arrays. Apparently in initial state, before loosing myself to complex constructions, my code was OK but it lacked just a one tiny bit: “return” for first element’s length. I wanted to do it, I stated it even in my post but then I lost myself to thinking that my function was somehow to blame. And the answer was in plain sight :stuck_out_tongue_winking_eye: “return longestWord[0].length;”

I solved it by looping thru the sentence and measuring and storing the length of each word in a variable, if the current word’s length was longer than the previous one, I overwrite the variable with the current word’s length, if not, I just went to the next word till the sentence was finished. I did not use the sort method, although I suppose you could. I did not change to lowercase because we weren’t asked to.

This was my solution (with some help from others on the forum):

function findLongestWord(str) {
  var wordLengths = str.split(' ').map(word => word.length).sort((a, b) => b - a);
  return wordLengths[0];
}