I'm Stuck whith for loops [resolved]

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]

thanks for your help

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;
}
1 Like

Thank you Pethaf you saved me ! :smiley:

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 !

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;
}

1 Like

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