Refactoring Find the Longest Word in the String

Can someone help and review my solution for the algorithm? :

function findLongestWord(str) {
var compare = [];
var poop = str.split(" ");
for(var i=0; i < poop.length; i++){
compare.push(poop[i].length);
}
return Math.max.apply(null, compare);
}

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

*I got the Math.max.apply(null, x) from MDN.
I googled other people’s solutions and it seemed like my way of solving it was not efficient. Let me know what you think!

Since you have already seen some other solutions, here is another way:

function findLongestWord(str) {
  var poop = str.split(" ");
  return Math.max(...poop.map(function(val){
    return val.length
  }));
}
findLongestWord("The quick brown fox jumped over the lazy dog")

In ES2015, Math.max can be used with the spread operator and an array. Also, you can use .map to make it functional and shorten it up a bit.

@joelc13, you could get the longest word itself (jumped) from the function, and then apply .length to the result…
See codepen for this…

function findLongestWord(str) { return str.split(" ").reduce(function(prev, val, i) { return val.length > prev.length ? val : prev; }); } document.write(findLongestWord("The quick brown fox jumped over the lazy dog").length)

1 Like