Skip to content

Instantly share code, notes, and snippets.

  • Select an option

  • Save anonymous/a2bf97fa67bfe2df130b to your computer and use it in GitHub Desktop.

Select an option

Save anonymous/a2bf97fa67bfe2df130b to your computer and use it in GitHub Desktop.
http://www.freecodecamp.com/v3rse 's solution for Bonfire: Find the Longest Word in a String
// Bonfire: Find the Longest Word in a String
// Author: @v3rse
// Challenge: http://www.freecodecamp.com/challenges/bonfire-find-the-longest-word-in-a-string?solution=function%20findLongestWord(str)%20%7B%0A%20%20%2F%2Fs%5Blit%20the%20string%0A%20%20var%20strArray%20%3D%20str.split(%22%20%22)%3B%0A%20%20%0A%20%20%2F%2Ffind%20the%20longest%20word%20in%20the%20array%0A%20%20strArray.sort(function%20(a%2Cb)%20%7B%0A%20%20%20%20if(a.length%20%3C%20b.length)%7B%2F%2Fif%20a%20is%20shorter%20move%20b%20down%0A%20%20%20%20%20%20return%201%3B%0A%20%20%20%20%7Delse%20if(a.length%20%3E%20b.length)%7B%2F%2Fif%20b%20shorer%20move%20a%20down%0A%20%20%20%20%20%20return%20-1%3B%0A%20%20%20%20%7Delse%7B%0A%20%20%20%20%20%20return%200%3B%0A%20%20%20%20%7D%0A%20%20%7D)%3B%0A%20%20console.log(strArray)%3B%0A%20%20return%20strArray%5B0%5D.length%3B%0A%7D%0A%0AfindLongestWord(%22The%20quick%20brown%20fox%20jumped%20over%20the%20lazy%20dog%22)%3B%0A
// Learn to Code at Free Code Camp (www.freecodecamp.com)
function findLongestWord(str) {
//s[lit the string
var strArray = str.split(" ");
//find the longest word in the array
strArray.sort(function (a,b) {
if(a.length < b.length){//if a is shorter move b down
return 1;
}else if(a.length > b.length){//if b shorer move a down
return -1;
}else{
return 0;
}
});
console.log(strArray);
return strArray[0].length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
@v3rse

v3rse commented Nov 23, 2015

Copy link
Copy Markdown

Used the sort function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment