Basic Algorithm Scripting - Find the Longest Word in a String

Tell us what’s happening:
Alright so, first of all I want to say that I know that this code is way more complex than it needs to be. I usually just try to brute force these problems until I get the right answer then I refine and simplify my code.

Anyway, when I run this code on runjs.co it works for “The quick brown fox…” and returns the correct number. When I run it with any of the other provided values of `str` I get “Uncaught RangeError: Invalid array length” on line 17 (`index++;`). Is anyone able to explain why?

Further, I am unable to run this code on fCC itself because it times out, is this just because there’s too much recursion happening?

``````function findLongestWordLength(str) {
let myArr = [...str];
let myArr2 = [];
let myArr3 = [];
let length = 0;
let index = 0;
for (let i = 0; i < myArr.length; i++) {
for (let j = index; myArr[j] != " "; j++) {
myArr2.push(myArr[j]);
}
if (myArr2.length > length) {
length = myArr2.length;
myArr3 = myArr2;
myArr2 = [];
} else {
myArr2 = [];
index++;
}
}
str = "";
for (let i = 0; i <myArr3.length; i++) {
str += myArr3[i];
}
return str.length;
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");
``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.50`

Challenge: Basic Algorithm Scripting - Find the Longest Word in a String

For your first loop over `i`, do you want to visit every single letter or every single word?
Also, the variable names `myArr`, `myArr2`, and `myArr3` make it really hard to follow what you mean this code to represent. Some clearer names would really help other people understand and help.