Question about the example code

Can someone explain how the following code evaluates to 11? I do not see how the 0 and 1 index in [3][0][1] is being figured.

var arr = [
  [1,2,3],
  [4,5,6],
  [7,8,9],
  [[10,11,12], 13, 14]
];

arr[3][0][1]; // equals 11

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36.

Challenge: Access Multi-Dimensional Arrays With Indexes

Link to the challenge:

I’m assuming you understand basic array indexing, such as

const array = [1, 2, 3]

and thus array[0] is 1 and array[1] is 2 and array[2] is 3.

Now lets replace the first value in the array with another array:

const array1 = [[4, 5, 6], 2, 3]

So now the value of array1[0] is the array [4,5,6]. And if you wanted to get a specific value in that array then you would access it the same way as any other array. So if we want to get the first value in that array then we would access it as:

array1[0][0] which gives us the value 4.

Which you could think of as

[4, 5, 6][0]

which means give me the first value of the array [4, 5, 6]. We just replaced array1[0] with its actual value (which is [4,5,6]).

Hopefully you can see now that if the array in array1[0] also had an array in it then we would go three levels deep in indexing to get a value in that array.

2 Likes

Thank you! I was staring and staring and forgot to consider the first array brackets wrapping the whole thing. Excellent detail in your answer, and I appreciate it.