Find the Longest Word in a String - why doesn't return 19?

Hey everyone,

This code doesn’t work when used on the following string: “What if we try a super-long word such as otorhinolaryngology”. It should return 19 because this is the length of the longest word, but instead, it returns 4. I can’t figure out why is it happening. Please help me to understand, and hope you have a great day :slight_smile:

Tell us what’s happening:

Your code so far



function findLongestWordLength(str) {
var myLenght;
var numbers = [];
var i;
  var arr = str.split(" ");
for (i = 0; i < arr.length; i++) {
  myLenght = arr[i].length;
  numbers.push(myLenght);
}
numbers.sort();
  return numbers.slice(-1)[0];
  
}


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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string

Your sort function is the problem. The default sort function doesn’t sort by increments.

Pass in this function

numbers.sort(function(a, b){
  return a-b;
});
1 Like

Thank you for your help! I have read about the sort and compare functions, I think now understand how it works!

1 Like

javascript

let myStr = "What if we try a super-long word such as otorhinolaryngology";

function findLongestWordLength(str){
    let longestWord = str.split(" ").reduce(
        (x,y) => x.length > y.length ? x : y
    );
    return longestWord.length
}
console.log(findLongestWordLength(myStr));

That should give you 19.

I would advice against using sorting since sorting is an expensive operation being O(N*lg(N)).

This can be solved with a O(N) solution.

Thank you that was my first post. I did not realize we weren’t allowed to spoil solutions! I’ll make sure to use [spoiler] tags next time.