# I'm Stuck whith for loops [resolved]

I'm Stuck whith for loops [resolved]
0

#1

Hello again,

Have a probleme with another challenge again…

Why my for loops isn’t iterating my code ?

``````
function largestOfFour(arr) {
// You can do this!
for(var i=0; i<4;i++){
var newArray = [];
var pushIt = newArray.push(Math.max.apply(null, arr[i]));
return newArray;
}
}

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

It works but only for the first sub Array -> [5]
I would like it to push evey Math.max in one array -> [5, 27, 39, 1001]

#2

Your code reassigns the name newArray to an empty array on each iteration, and returns a newly assigned value at the end of the iteration but never does anything with the returned value.

You probably want something like.

``````function largestOfFour(arr) {
var theMaxes = [];
for(var i=0,j=arr.length;i<j;i++) {
theMaxes.push(Math.max.apply(null, arr[i])); //Add to array that exists outside of for-loop.
}
return theMaxes;
}
``````

#3

## Thank you Pethaf you saved me !

I’m on it since this morning, trying to find what’s wrong, I think i’ve not understood yet how “for loops” works.
In your solution everything is ok, you just have to change “j++” by “i++” and it’s ok!

Thank you again !

#4

I realized this code can be made even shorter,

``````function largestOfFour(arr) {
var theMaxes = [];
arr.forEach(function(subArr) {theMaxes.push(Math.max.apply(null,subArr));});
return theMaxes;
}

``````

#5

As @Pethaf said, you reassign an empty array to newArray during each iteration of the for loop. Also, you only get one iteration of the for loop, because your return statement is inside it. That is why you get the first sub array of [5] returned, but nothing else.

To fix your existing code, move the newArray assignment to before the for loop and move the return newArray to just outside of the for loop, then you can do the following:

``````function largestOfFour(arr) {
var newArray = []; // outside for loop
for(var i=0; i < 4 ;i++){
newArray.push(Math.max.apply(null, arr[i]));
}
return newArray; // outside for loop
}
``````

#6

Thank you for your help I think I’ve undestood my mistakes !