Return Largest Numbers in Arrays - Too many loops?

Return Largest Numbers in Arrays - Too many loops?
0

#1

Hi,
My code should take an array of 4 sub arrays, get the maximum values of each and return an array of these values, here is the link to the challenge.
Here is my code:

function largestOfFour(arr) {
  let results = [];
  let max = 0;
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr[i].length; j++) {
      for (let y = 0; y < arr[i].length; y++) {
        if (arr[i][j] < arr[i][y]) {
          results[i] = arr[i][y];
          max = arr[i][y];
        }
      }
    }
  }
  return results;
}
largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]));

Returns : [ 9, 35, 97, 857 ]

The loops look ugly :), I’m just trying to get it working before i try to figure out how to optimize it, the problem here is that when (y) hits the end, it loops again incrementing (j) and comparing again which unnecessary and which causes to forget the first values each time,
Could you give me a hint on how to fix this,
Thank you,


#2

You are given a single array to begin with, so that needs a loop to find the four things inside it.
The four elements of the array are also arrays, so you need a single loop for those. (To loop over their contents).
That’s it, there are no more subarrays and therefore no more loops are needed.


#3

I added the third loop in order to increment (y) while (j) is = 0, I could not do my comparisons (arr[i][j] < arr[i][?], arr[i][j+1] does not do it),