# Find the longest word - Question about my solution [Title changed]

Hello together,

I actually stuck on the “Find the longest word” challenge.

First this is my idea how I can make it:

1.) .split() the string into an array (This is clear.)
2.) With .sort() I sort the words.
3.) After that I have to return the longest word as a number.

My code looks like that:

``````  var myWords = str.split(' ');
myWords.sort(function(a,b) {
return a.length - b.length;
});
return myWords.length;
}
``````

But this will give me only the number of words and not the longest word. The third point of my idea isn’t ready.

How could I solve this? Any tipps?

Wish you a good day,

Markus

I have a solution:

``````  var myWords = str.split(' ');
var maxLength = 0;

myWords.sort(function(a,b) {
return b.length - a.length;
});

return myWords[0].length;
}
``````

I have make a variable for the maxLength with 0 and change the return in my .sort() function. Also I have make a change to my return with the [0].

This solution will work but is it a good solution?

var long="",
text=“Hello markusdunkel how are you”,
arr=text.split(" "),
x=arr.sort(function(a,b){
if(a.length>b.length){
return 0;
}
else{
return 1;
}
});
console.log(x[0]);

@markusdunkel It is a good solution. As a challenge to yourself, see if you can solve it in two more ways.

1st) Using the split as you have done already, but without the extra sort step

2nd) Without using arrays at all (this is the most efficient solution for extra long sentences which are beyond the scope of this problem)

If you try these solutions above and need some guidance, I can help point you in the right direction. Hopefully, if anyone else posts a solution to one of the ways I have suggested above, they will use the spoiler tag to blur out their answer.

@rmdawson71 @AzerLabrin thx for your help.

@rmdawson71 I will try if I can solve this challenge in two more ways like you say. When I’m get stuck I will write here in this topic or when I’m ready with this personal challenges.