# Find the Longest Word in a String 2

``````function findLongestWord(str) {
var strar = str.toLowerCase().split(' ');
var ckr=0;
for (var i=0;i<=strar.length-2;i++)
{
if(strar[i].length >= strar[i+1].length)
{
ckr = strar[i].length;
}
else
{
ckr = strar[i+1].length;
}
}
return ckr;
}

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

// code ended.
``````

Don’t know why it satisfies 3 test cases but not other 3

failed for following test cases

1. findLongestWord(“The quick brown fox jumped over the lazy dog”) should return 6.

2. findLongestWord(“May the force be with you”) should return 5.

3. findLongestWord(“What is the average airspeed velocity of an unladen swallow”) should return 8.

One big problem with your solution is that you are only ever comparing two consecutive words. In the sentence “The quick brown fox jumped over the lazy dog”, the correct answer is 6, because “jumped” is the longest word. You do assign the value 6 to chr when “jumped” is encountered, but you when your code compares “over” to “the”, ckr becomes 4 and stays 4, because “lazy” which also has length of 4 gets compared to “dog” in the last iteration of the for loop.

1 Like

Thanks a lot, I nailed it
here is my code made changes at line number 6 and 10.

``````function findLongestWord(str) {
var strar = str.toLowerCase().split(' ');
var ckr=0;
for (var i=0;i<strar.length-1;i++)
{
if(strar[i].length >= strar[i+1].length && strar[i].length >= ckr)
{
ckr = strar[i].length;
}
else if (strar[i+1].length >= ckr)
{
ckr = strar[i+1].length;
}
}
return ckr;
}

findLongestWord("The quick brown fox jumped over the lazy dog");
``````

Another potential solution would be to split the string into an array, like you do, and then sort the array from longest to shortest, and then return the length of the first element of the array which will be the longest word.

@willgreenzilla you are right, I thought about bubble sort or insertion sort but they require multiple iteration whereas the above code will work in single iteration as we need only the longest word and not sorted list of all words