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?

Hello , i hope this code will help you
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]);

@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.