For Loops for nested arrays

**Hi all - I was working on the Return Largest Numbers in Arrays exercise. I passed it but was left with a question. Don’t we need to use for loops twice when dealing with arrays within arrays ? are there exceptions? It obviously didn’t work here…at least for me. Just trying to understand for loops better.
Thanks for your help!

for(var i =0; i < arr.length; i++){
  var sortingEachArr= arr[i].sort(function(a,b){
    return a-b;
  })
for (var j = 0; j<arr[i].length; j++){
}

  **Your code so far**

function largestOfFour(arr) {
var largestNumbers = [];
for(var i =0; i < arr.length; i++){
  var sortingEachArr= arr[i].sort(function(a,b){
    return a-b;
  })
    var x = arr[i][arr[i].length-1];
    
  largestNumbers.push(x);
  
}
return largestNumbers;
}

console.log(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 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36

Challenge: Return Largest Numbers in Arrays

Link to the challenge:

By sorting the nested array in the order shown, smallest to largest, we no longer need the inner loop - we know we moved the largest value to the end of that inner array each time, so we can just pluck that value.

Ordinarily, you’d be right, and i don’t care for the given approach as the original arrays have been sorted in place, which can be a dangerous side effect.

2 Likes

Thank you so much. It makes sense. I appreciate the help!

1 Like

Just in case this isn’t clear.

The sort method is your second loop. The sort method loops the array in order to sort it. So you have two loops you just didn’t write the second loop yourself.

1 Like

Thanks. I didn’t think of the sort method as a loop. I appreciate your help.