Tell us what’s happening:
Describe your issue in detail here.
Can you explain to me why this code is not solves the problem and returns NaN, please?
**Your code so far**
function findLongestWordLength(str) {
let arr = [];
for(let a = 0; a < str.length; a++){
arr.push(str[a].length);
}
return Math.max(arr);
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36
Hi, here you are simply traversing through each character of string, here str.length will be the length of the entire sentence, str[a] here will denote each character and not a word, hence max(arr) sent for each sentence will be 1 only i.e length of a character:
for(let a = 0; a < str.length; a++){
arr.push(str[a].length);
}
In your for loop, you are actually not inserting the length of each word rather inserting the count of each character from your string(which will always be 1)
Try logging the arr in the console, you’ll find that.
Math.max method won’t work directly on the array you will have to use the spread operator. Read more about the Math.max here