Remember Array methods? Good! We’ll be using them again today. Today’s challenge, “Find the Longest Word” will have us write a function that takes a string and returns the length of the longest word in that string.
It’s pretty straight forward, “human like” instructions would be something like:
- Split the string in single words.
- Word by word, count the number of letters.
- Return the length of the longest word.
We know how to split a string and turn it into an array. We know how to loop through items in an array and we know how to get the length of a word. So let’s give it a shot:
function findLongestWord(str) { var wordArray = str.split(' '); var longestWord = ''; for (var i = 0; i < wordArray.length; i++) { if (wordArray[i].length > longestWord.length) { longestWord = wordArray[i]; } } return longestWord.length; }
And that’s it. We define a new variable longestWord and set it to an empty string (with length 0). We split out string into an array by splitting at every space character. We then loop through the word array, and every time a words length is greater that the length of longestWord, set longestWord to this word. We then return the length of whatever word ended up inside longestWord.
But this seems so easy and too fast doesn’t it. We don’t we do some of the obscure stuff we love? Let’s use some functional programming. Functional programming can be tedious to get into, and if you prefer, you can just skip over and wait until FreeCodeCamp teaches you it’s intricacies. But, if you’re like me, and love going ahead of yourself, take this as a little challenge. (Tip: In the reduce method, we are passing a function with two arguments, curr and next. curr refers to the current item in the array, and next refers to the next item in the array. Reduce does the following in this function, it compares the current array item to the next and returns the longest one. It then does the same for every other item in the array.)
Here’s the same findLongestWord function, using the the reduce method.
function findLongesWord(str) { return str.split(' ').reduce(function(curr, next) { return curr.length > next.length ? curr : next; }).length; }
Oh wow, that look confusing. Actually it is not all that complicated. We are just concatenating methods here. We are turning our string into an array, then using the reduce method in conjunction with the tertiary operator to get the longest word in the array and finally passing the length method so that the value returned in the length of this longest word.
Look at the code, and look at it hard. This time I’ll have you try to figure it out, and once you do, try using the replace method used in the previous lesson to first get rid of punctuation.
Good luck, have fun, and post a comment if you get stuck or need some insight!