# Basic Algorithm

I’ve been working on this algorithm for almost a day and cant get it to work. It’s the ‘return largest number in arrays’. Please help.

``````
function largestOfFour(arr) {
// You can do this!
let largestNum = 0;
for(let i = 0; i <= arr.length; i++){
for(let j = 0; j <= arr[i].length; j++){
if(arr[i][j] > largestNum){
largestNum = arr[i][j];
}
}
}

return largestNum;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

``````

You are getting the ​"TypeError: Cannot read property ‘length’ of undefined" message, because you are trying to reference an element in arr (arr) which does not exist. The reference to arr is undefined, so when you attempt to get the length of arr in the inner for loop condition (shown below), you get the message because undefined does not have a length property.

``````for(let j = 0; j <= arr[i].length; j++){
``````

Why are you even referencing a non-existent element? Because you have accidentally forgotten that arrays are zero-indexed, so the highest index for an array with 4 elements will be 3. The problem is your outer for loop condition (shown below), uses <= instead of <, which allows i to go to 4.

``````for(let i = 0; i <= arr.length; i++){
``````

Fixing both of the for loop conditions will not completely solve the challenge for you, but will fix the errors causing your code to hault.

Yes. errors are gone. I’m only getting the largest of the last sub-array though.

That is because as you get the largestNum for each sub array, you need to be building a final array which will hold each largestNum, so you can return the final array at the end, instead of just the largest largestNum overall.

HINT: After the inner for loop completes each time, largestNum will be the largest number for the sub array (arr[i]) which was just iterated.

Got it. Thx for the help.

Thought I had it done. The algorithm works fine on the browser console but doesn’t pass fcc tests. If someone can tell me why, that would be great.

``````
function largestOfFour(arr) {
// You can do this!
for(let i = 0; i < arr.length; i++){
let largestNum = 0;
for(let j = 0; j < arr[i].length; j++){
if(arr[i][j] > largestNum){
largestNum = arr[i][j];
}
}