Help with largest numbers in array challenge

Tell us what’s happening:
My code will execute the first three tasks properly but fails for the last task and I think it might have to do with the negative numbers. Looking at solution 1, my code is very similar except that I have defined ‘largestSub = 0;’ out side of the for loop. If I move this line outside of the inner for loop it still fails. I am curious as to why the solution defines theirs as’ largestNumber = arr[n][0];’. Why wouldnt it just be ‘largestNumber = 0’?

Your code so far


function largestOfFour(arr) {
var largestNum = [];
 var largestSub = 0;

  for(var i = 0; i< arr.length; i++){
   
    for(var j = 0; j < arr[i].length; j++){
      if(arr[i][j]>largestSub){
        largestSub = arr[i][j];
      }
       
    }
    largestNum.push(largestSub);
       largestSub = 0;
    
  }
return largestNum;

}

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.146 Safari/537.36.

Challenge: Return Largest Numbers in Arrays

Link to the challenge:

Hi @jlala !

Welcome to the forum!

I have edited the title of your post to remove the link for the challenge.

Try to avoid pasting links in the title since users can not click on them.

With the revised title you should get more responses to your questions.

Happy coding!

1 Like

You actually answered your own question with the first sentence. Your code currently assumes that the largest number is always greater than 0. The solution code doesn’t make such an assumption, it just starts with the first number in the array.

Ah…that makes sense. Thank you!