Tell us what’s happening:
Logically, my code should work, however my syntax or approach must be off somewhere. ‘let strLength = strBuffer.length;’ returns the type error in the console log however, since assigning the variable ‘strBuffer’ to ‘strArr[i]’, I get the lengths of each word isolated getting me the numbers into an array, ‘trackWordLength’, at their respective places.
So to my question, how come in the second for loop I cannot access the ‘trackWordLength’ array items using ‘trackWordLength[j]’ and ‘track
Your code so far
let codingRegex = /\w+/g; // extracts words to an array...
let trackWordLength = [];
function findLongestWordLength(str)
{
let strArr = str.match(codingRegex); // 1st for loop; creates array w/ each word at own position/index then creates array with each words length at respective positions
let largestNum; // 2nd for loop; will store largest number after each loop executes
for (let i = 0; i <= strArr.length; i++) // iterates through each word in array
{
let strBuffer = strArr[i];
// can still access 'length' but getting error: 'Cannot read properties of undefined (reading 'length')
let strLength = strBuffer.length;
//takes word 'i' length and pushes it to array 'trackWordLength' for access in 2nd loop
trackWordLength.push(strLength);
console.log(trackWordLength);
}
// compares number at index 'j' to all other numbers, then returns the largest
for (let j = 0; j <= trackWordLength.length; j++)
{
if (trackWordLength[j] >= trackWordLength[j++])
{
largestNum = trackWordLength[j];
console.log(largestNum); // not logging anything
}
else
{
largestNum = [j++];
console.log(largestNum); // not logging anything
}
}
return largestNum;
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36
Challenge Information:
Basic Algorithm Scripting - Find the Longest Word in a String