Basic Algorithm Scripting - Find the Longest Word in a String

Tell us what’s happening:
Hi! findLongestWordLength("What if we try a super-long word such as otorhinolaryngology") should return 19. is the only one that is not checked. Can you help me pls? Mozilla Console says that return is not in the function but I think it is!!
Your code so far

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

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; rv:109.0) Gecko/20100101 Firefox/117.0

Challenge: Basic Algorithm Scripting - Find the Longest Word in a String

Link to the challenge:

The issue is your use of the sort method. By default, the array is sorted lexicographically, which means the following:

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(arr.sort())

…will print [1, 10, 2, 3, 4, 5, 6, 7, 8, 9] to the console.

You will instead need to make your array sort numerically.
As an aside, you don’t need to do this inside the for loop btw, because then you’d be sorting it every single time you push a new value. You could instead sort it once, directly before the return statement.

1 Like

Okay thank you so much, Math.max(); done what I was hoping for. thank you again showing me another way :upside_down_face:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.