Challenge:
Return the length of the longest word in the provided sentence.
I've made a solution that works but it is kinda bad since the time complexity is \$O(n \log n)\$ and it involves mutation.
function findLongestWordLength(str) {
let strSplit = str.split(" ");
let wordLengthArray = [];
for(let i = 0; i < strSplit.length; i++)
{
wordLengthArray.push(strSplit[i].length);
}
wordLengthArray.sort(function(a , b){return a - b});
return wordLengthArray[wordLengthArray.length - 1];
}
I basically split the string, pushed all the word lengths in an empty array, then used the ascending sort function. After that I returned the last index of the new array which is the longest length.
Test Cases:
findLongestWordLength("The quick brown fox jumped over the lazy dog") should return 6.
findLongestWordLength("May the force be with you") should return 5.
findLongestWordLength("Google do a barrel roll") should return 6.
findLongestWordLength("What is the average airspeed velocity of an unladen swallow") should return 8.
findLongestWordLength("What if we try a super-long word such as otorhinolaryngology") should return 19.
I would appreciate some hints/tips on a better algorithm.