Find the Longest Word in a String_New

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

Challenge: Find the Longest Word in a String

Link to the challenge:

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);
}

Improve the logic and it will work.

1 Like

Hi,
I can see 2 problems in your code.

  1. 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.

  2. 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

1 Like

it’s returning NaN because you used Math.max([ 1,2,3,4 ]) but it should be like
Math.max(1,2,3,4,5,6) to get that you should spread the array with …

For debugging purpose you can try this line inside the for loop

console.log(str[a].length)

then you’ll get the reason for wrong answer

Hint :- first try to split the string with whitespaces to get individual words

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.