I just finished this challenge. I feel like I’m finally starting to grasp JS and how it works, I didn’t have to Google or cheat to finish this one, I did it all from scratch. Just looking for some feedback if I could simplify this any more. Thanks all.
function findLongestWord(str) {
var myWords = [];
var myWordsLength = '';
var myWordsArr = [];
var longest = 0;
myWords = str.split(' ');
for (i = 0; i < myWords.length; i++) {
myWordsLength = myWords[i].length;
myWordsArr.push(myWordsLength);
}
for (i = 0; i < myWordsArr.length; i++) {
if (longest < myWordsArr[i]) {
longest = myWordsArr[i];
}
}
return longest;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
So you have an input with a long string with multiple words in it. The only output you need is the length of the longest word, so you need to know which is the longest word in the string.
Your code has a first loop that creates an array with the length of each word, then a second loop to identify the highest value in myWordsArr.
You really need only the logic of the second loop.
To push further, you could look into using .filter() and .reduce().
It’s pretty good. It’s nice that you’re keeping track of variables because it’ll help you keep track of relevant data in later challenges. However, you only really need one for loop for this challenge.
for(var i = 0; i < myWords.length; i++){
if(longest < myWords[i].length){
longest = myWords[i].length;
}
}
This isn’t really a problem for this challenge, but generally you don’t want to iterate through an array more than you need to. The performance hit becomes more noticeable the longer the array. If the array was, say, 1000 items long, that’s 1000 more items it has to go through again.
There are convoluted single-line solutions for this challenge but you don’t have to worry about them just yet.
function findLongestWord(str) { var max = 0; var wordList = str.split(' '); for (var i = 0; i < wordList.length; i++) { max = wordList[i].length > max? wordList[i].length: max; } return max; }
function findLongestWordLength(str) {
let arr = str.split(" ").sort(function(a, b){
return a.length < b.length
});
return arr[0].length;
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");
Your solutions are very clever, @c0ka and @lionel-rowe. I didn’t think about using .map() and Math.max .