Return Largest Numbers in Arrays storage question

Tell us what’s happening:

  **Your code so far**

function largestOfFour(arr) {
let results = [];
for (let i = 0; i < arr.length; i++) {
  let largestNumber = arr[i][0];
  for (let j = 1; j < arr[i].length; j++) {
    if (arr[i][j] > largestNumber) {
      largestNumber = arr[i][j];
    }
  }
  results[i] = largestNumber;
}

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

Challenge: Return Largest Numbers in Arrays

Link to the challenge:


So, I understand the majority of this code but I’m really confused as to how the storage and evaluation works. When I log certain elements of the code such as largestNumber before the inner loop, i get the first value of each inner array
which makes sense, however it gives me the format:
4
13
32
100
which are not arrays. When I use typeof it just tells me they’re numbers and when I try to use console.log(largestNumbers[0] or [i]0, it gives me undefined . I don’t quite understand what they are exactly. Furthermore, how is evaluation taking place if these numbers don’t have any array coordinates. How does arr[2,2] know to compare against 32 and not 4? How is the position of 32 determined?

largestNumber is not an array. It is a single number. It is the value from either arr[i][0] or arr[i][j], depending on when you’re talking about it.

largestNumber holds a single value that later values are compared against. It will always be the highest number found so far (in this outer loop), so there is only one number to compare against.

It isn’t? I’m not sure what you mean.

1 Like

I think i understand what you’re saying now, once it finds the highest number for that particular array, it moves to [1][0] and runs down anything in [1][i]. For some reason, I assumed all 4 initial numbers were generated at one time so I didn’t quite understand how the array panels could find the right corresponding number to compare against.

HI @hereforfreebie !

Welcome to the forum!

It sounds like there is confusion about nested arrays.

This part here says to grab the first number of each nested array.

So when i is two then the largestNumber at arr[2][0] is 32.
Remember that arrays are zero based index.
Hope that helps!

let vals = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];

vals is a nested array (an array of arrays).
vals[0] is the first element of the array, which is [4, 5, 1, 3],
vals[1] is [13, 27, 18, 26], and so forth.
If you write

let x = vals[0]; 
let y = x[0];
let z = vals[0][0];

both y and z have the value 4. JS uses a sequence of brackets to access the nested elements.
vals[2] is [32, 35, 37, 39] so vals[2][0] is 32, vals[2][1] is 35, and so forth.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.