I am trying to write a basic javascript function to find the longest word in a string and log it\'s length.
So far I have:
function findLongestWord(
You can greatly simplify this using Array.prototype.sort and Array.prototype.shift. For example
var str = 'The quick brown fox jumped over the lazy dog',
longest = str.split(' ').sort(function(a, b) {
return b.length - a.length;
}).shift();
document.getElementById('word').innerHTML = longest;
document.getElementById('length').innerHTML = longest.length;
The sort() will produce an array of strings sorted by their length (longest to shortest) and shift() grabs the first element. You could also sort the other way (shortest to longest) using return a.length - b.length and pop() instead of shift() to grab the last element.