Return Largest Number in Array Challenge - Question

Hi All,

I completed the solution to this challenge (see below if required). However, I was wondering why I didn’t need to do a nested for loop? I thought this was a nested array? Theoretically I thought it should have worked as my example 2. Can someone expand on this for me please?

function largestOfFour(arr) {
var newArray = [];

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

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

what I thought it was supposed to be below:

function largestOfFour(arr) {
var newArray = [];

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

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

In the second example, arr[i][j] evaluates to a single number. So it doesn’t make sense to do arr[i][j].sort() or you’ll get an error (the sort() function only applies to arrays; same with pop()).

You don’t need an inner loop because what you want to deal with aren’t the individual numbers, but the subarrays themselves.

Also, you don’t need to reassign arr[i], because sort() modifies the array in place.

@kevcomedia Thank you for your response! That makes a lot more sense. I didn’t think about how those two only applied to arrays.