var largestNumber = arr[i][0] This creates a variable which is set to the value of the first number within the sub array j. ( first character zero indexed in the inner array )
for (var j = 1; j < arr[i].length; j++) This cycles through all the numbers in the inner array starting with the second number in each array ( Its is getting compared to the first number arr[i][0]
Beautiful!
if(arr[i][j] > largestNumber) If the second number is larger than the first number in the arr it becomes the largest number and the comparison begins again with the new number eg. arr[i][1] against arr[i][2] and so on.
I think you understand this part, just to make it clearer I might word it as: “if the j
th number in arr[i]
is larger than largestNumber
, then set largestNumber
equal to the j
th number”.
If there is a problem up to this point I am not sure what is happening
Nope, looks great so far! There’s a couple of issues below though.
The next part largeArr.push(largestNumber); I only get in principal though I don’t get how it would keep cycling through. I think as it stands even if the rest of the code is correct this part would still only return you the higher of the comparison between the first and the second [0] and [1] with in the array.
Awesome, there is an issue here, so lets talk about it. So largeArr
starts as []
. largeArr.push(1)
would make largeArr = [1]
, and if you did largeArr.push(-3)
after that, then largeArr would equal [1, -3]
. Does that make sense? largeArr.push(N)
adds N
as the last element in largeArr
.
You understand your code pretty clearly up to this point. Here’s one of the arrays from your sample input: [32, 35, 37, 39]
, so lets suppose that we’re executing through your code. Currently, largeArr=[]
and i=0
. arr[0] = [32, 35, 37, 39]
. With this in mind, can you read through the outer for loop. What does largestNumber
equal at first? What does largeArr
contain when j=1
? what about when j=2
and j=3
?
Here’s probably a more important question: what do you want largeArr
to contain?
Given your sample input, arr=[[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]
, what should largeArr
contain at the very end of your function?