Find the longest word in a string challene

Find the longest word in a string challene
0

#1

https://www.freecodecamp.com/challenges/find-the-longest-word-in-a-string#?solution= function%20findLongestWord(str)%20{ %20%20var%20array%3Dstr.split("")%3B %20%20var%20number%3B %20%20 %20%20array.sort(function(a%2Cb) %20%20%20%20%20%20%20%20%20%20%20%20{ %20%20%20%20number%20%3Db.length%3B %20%20%20%20return%20a.length-b.length%3B %20%20%20%20 %20%20})%3B%0A%20%20return%20number%3B%0A%20%20%0A%7D%0A%0AfindLongestWord(%22The%20quick%20brown%20fox%20jumped%20over%20the%20lazy%20dog%22)%3B%0A

function findLongestWord(str) {
var array=str.split("");
var number;

array.sort(function(a,b)
{
number =b.length;
return a.length-b.length;

});
return number;

}

findLongestWord(“The quick brown fox jumped over the lazy dog”);

why does my code not return the correct number?


#2

First str.split("") makes a array of individual characters of the string … you need to put a space between the “” like so " " to make array of individual words. Then you are telling it to return number which number = b.length so in you case will be 1 because all characters are length 1 also this will return the length of last charterer in array as this is a sort.
you should use filter()… eg array.filter()… as this can compare the length of each word in your array and return the largest. you just need to create the code in the filter for what you want the filter to check for eg if word.length is greater than max (max being a variable you create to store a number) … max = word return max. Also you should use the developer tools or repl.it so you can walk though your code and see whats going on this will really help … this might make more sense and be of more help


#3

I think I used a completely different method to solve this ages ago, lol. sorry should have said!