Basic algorithm scripting Return largest Numbers in array

Hi,

Can anyone explain to me why this works in hardcoded:

function largestOfFour(arr) {

  var results = [];

  var largest = Math.max(...arr[0]);

  results.push(largest);

  var largest = Math.max(...arr[1]);

  results.push(largest);

  var largest = Math.max(...arr[2]);

  results.push(largest);

  var largest = Math.max(...arr[3]);

  results.push(largest);

  return results;

}

 

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

but it will not work if I out it through a loop? Because, the above cleared the challenge, but it was only to test if my theory was true, that it should work.

This is the code that does not work:

function largestOfFour(arr) {

for(var i = 0; i > arr.length; i++){

      var largest = Math.max(...arr[i]);

      results.push(largest);

}

 return results;           

}

I know there a lot of more elegant solutions than mine, I checked the hint section. But I can not for the life of me get why this won’t work….

the loop keep looping as long as the condition is true, yours start being false and the loop is never executed: i starts at 0, so it can never be bigger than arr.length

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.

1 Like

Thank you ieahleen, how han i have missed that :joy:

Ohh I did not realize that, I Will make sure to post IT wirh spoilers in the figure ud i have code snippets in the post.

1 Like