Dont understand arrays


#1

can someone pls explain how to access arrays
and why is the answer here is 6??

var myMultiArray = [
            [1,2,3,4,5, [1,2,3,4,5] ],
            [6,7,8,9,10 , [1,2,3,4,6] ],
            [11,12,13,14,15 , [1,2,3,4,5] ],
            [16,17,18,19,20, [1,2,3,4,5] ]
            ];

console.log( myMultiArray[1][5][4] ); // Outputs 6

#2

you have a array, inside this array you have 4 arrays:

first array:
[1,2,3,4,5, [1,2,3,4,5] ]
second array:
[6,7,8,9,10 , [1,2,3,4,6] ]
third array:
[11,12,13,14,15 , [1,2,3,4,5] ]
and last array:
[16,17,18,19,20, [1,2,3,4,5] ]

now, when you do myMultiArray[1] in exercise, you get the second array (counting start at zero), so this one:
[6,7,8,9,10 , [1,2,3,4,6] ]
now,
myMultiArray[1][0] would be 6
myMultiArray[1][1] would be 7
myMultiArray[1][2] would be 8
etcetera

now,
myMultiArray[1][5] would print out [1,2,3,4,6], why? because at index 5 there is another array. to access values in this array you need to specify the index:

myMultiArray[1][5][0] would print out 1
myMultiArray[1][5][1] would print out 2
myMultiArray[1][5][2] would print out 3
myMultiArray[1][5][3] would print out 4
myMultiArray[1][5][4] would print out 6

hope this helps


#3

Well access an array is pretty simple. The elements of the arrays are numbered so to get a specific element you just need to use arrayName[elementIndex]. The only uncommon thing is that you start counting at 0 so e.g to get the 3rd element in the array you have to ask for arrayName[2] because in the row 0,1,2 now 2 is the 3rd element.

For these multidimensional arrays you can go through in order so:

myMultiArray[1][5][4]

can be interpreted as

((myMultiArray[1])[5])[4]

meaning you get the 2. element of myMulitArray which is again an array of which you get the 6th element which is again an array of which you get the 5th element which is the value 6.

In the specific example myMultiArray has 4 main elements:

[1,2,3,4,5, [1,2,3,4,5] ]
[6,7,8,9,10 , [1,2,3,4,6] ]
[11,12,13,14,15 , [1,2,3,4,5] ]
[16,17,18,19,20, [1,2,3,4,5] ]

of which you pick the second because of myMultiArray[1]

this gives you the following array:

[6,7,8,9,10 , [1,2,3,4,6] ]

which has 6 elements:

6
7
8
9
1
[1,2,3,4,6]

of which you pick the 6th because of

((myMultiArray[1])[5])

Now this gives you

[1,2,3,4,6]

which has 5 arrays and if which you pick the 5th because of ((myMultiArray[1])[5])[4] and now you get the output 6.


#4

thank you guys this was so helpful!!!