Largest number in subarrays

I just want to clarify this logic, because I thought we would need to .push the largest number for each subarray into the new results array.
But it seems we can just write results[n] = largestNumber
Does it just automatically know to provide 4 separate numbers simply because we are iterating through 4 subarrays?
It’s just not very clear to me that 4 separate numbers will definitely be displayed in the final array.

function largestOfFour(arr) {
  var results = [];
  for (var n = 0; n < arr.length; n++) {
    var largestNumber = arr[n][0];
    for (var sb = 1; sb < arr[n].length; sb++) {
      if (arr[n][sb] > largestNumber) {
        largestNumber = arr[n][sb];
      }
    }

    results[n] = largestNumber;
  }

  return results;
}

results is an array
n has values 0,1,2,3

so you have

results[0] = ...
results[1] = ...
results[2] = ...
results[3] = ...

it’s because you are writing it to have 4 numbers, it doesn’t automatically know anything
or, it has 4 numbers because you have 4 sub-arrays yes, but it’s not direct, it’s just because your loop goes from n = 0 with condition n < arr.length

1 Like