Return Largest Numbers in Arrays confused about subarrays

Return Largest Numbers in Arrays confused about subarrays
0
#1

Tell us what’s happening: I understand how to solve this problem if we are just looping through one array but I dont really understand how to do when we add the other 3 sub arrays in.

Right now my code returns: [4, 5, 5, 5,]

``````
function largestOfFour(arr) {
// You can do this!
var result = [];
var largeNum = 0;
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < 4; j++) {
if (arr[i][j] > largeNum) {
largeNum = arr[i][j];
}
result.push(largeNum);
}
return result;
}
}

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

Your Browser User Agent is: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36`.

0 Likes

#2

Currently you have return result; within your outer for loop. Remember, that when a return statement is encountered, the function is exited immediately and returns the value specified. Because your return statement is inside the outer for loop, you only get one iteration of the outer for loop before it is exited.

But why does you result array have 4 values in it? Because your result.push(largeNum); is inside your inner for loop, so you get 4 pushes (one for each element in the first inner array of arr). Why is [4,5,5,5]? Because, during the first iteration of the inner for loop, 4 is larger than 0. During the second iteration of the inner for loop, 5 is larger than 4. Also, since 5 is larger than 1 and 3, 5 gets pushed two more times, before the function is exited due to the return statement placement.

These issues are easily fixed by moving the statements to the correct location, but you will still have a final problem, because of another misplaced declaration/assignment:

``````var largeNum = 0;
``````

Since you assign largeNum before any of the for loops begin, it will never be reset back to 0, so largeNum will keep the value it has at the end of the last time it iterated through the inner for loop. You just need to move this declaration to be inside the outer for loop.

0 Likes

#3

Okay that you for clearing that up!

I moved the return out of the for loops and put the largeNum var inside the outer loop and now what im getting to return is [4,5,13,27,32,35,37,39,1000,1001]

0 Likes

#4

That is probably because your push is still inside the inner for loop instead of outside it.

0 Likes

#5

Of course! Thank you so much for your help!

0 Likes