Can someone explain what's happening in this code line by line?

Can someone explain what's happening in this code line by line?
0

#1

I’m having a tough time understanding what happens in every loop for it to eventually get the result it does.

Also, to help me understand the sort method, what values are passed in for a and b?


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

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


#2

Try reading the documentation for sort first, because it does a good job of explaining what the function parameters (a,b) are.


#3

So whole goal of this function is to sort the numbers from smallest to greatest. Luckily, Javascript has a built-in function to help us do this (array.sort()).

But, in our problem, we have an array of arrays, hence the for loop. Now that we have the for loop, we have access to each nested array (arr[i] is a nested array).

Now we want to sort each of those arrays from smallest to greatest. We can do this using Array.sort() (You can read more about sort by going back through the challenges or just googling it). All the return b - a line means is sort this nested array’s elements from smallest to largest.

After it’s sorted, we store the results in an array called results (as array.sort does not modify the array it was called on).

And finally, we return our result.