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.
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.
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.