Skip to content

Instantly share code, notes, and snippets.

@AdrianSkar
Last active April 23, 2018 14:40
Show Gist options
  • Save AdrianSkar/ff86c044e34721f078179f92f2f754d6 to your computer and use it in GitHub Desktop.
Save AdrianSkar/ff86c044e34721f078179f92f2f754d6 to your computer and use it in GitHub Desktop.
function findLongestWord(str) {
//Split input by spaces
var a = str.split(" "); // Use /\W|_/ instead to match non alphanumeric or underscore chars
//New array for lengths
var b = []; // c=""; for later returning which one (not needed for this exercise)
for (i=a.length-1; i>=0 ; i--){
//Iterate trough "a" and save lengths to "b"
b[i] = a[i].length;
// if (c.length < a[i].length){c=a[i];} Will store which word is the longest in "c"
}
//sort (longest first)
function comp(d, e){
return e - d;
}
b.sort(comp);
//return longest length
return b[0] // + " chars: " + c; to return which one
}
findLongestWord("The quick brown fox jumped over the lazy dog");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment