After splitting the string into an array of words, my code won’t return the number of the longest word in the string. Any help in what could be the problem? Your code so far
function findLongestWordLength(str) {
return str.split('')
.reduce(function(x,y) {
return Math.max(x, y.length)
}, 0);
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");
findLongestWordLength("May the force be with you");
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36.
Hello, thank you for your quick reply, after inserting the console.log(arr) statement, it does break down the string into the words, but my code still won’t return the length value of the longest word.
you are comparing the length of each string inside the array, all of them have length 1, there is nothing in there with length of 5, so from reduce the value that come out is 1
You have not broken down the string into the words, but into the letters.
Hello ieahleen, thank you for your input. I have re-done my code below, and I am still getting an issue where it is not denoting the number that corresponds to the length of the longest word in the string. All it does is return the number 1. If you have any insights on this, it would be much appreciated. Thank You,
function findLongestWord(str) {
var strSplit = str.split(' ');
var longestWord = 0;
for(var i = 0; i < strSplit.length; i++){
if(strSplit[i].length > longestWord){
longestWord = strSplit[i].length;
}
}
return longestWord;
}
findLongestWord("The quick brown fox jumped over the lazy dog");