Reputation: 65
I have some data in the format of
[[12, 23],[27,-6],[52, -32],[82, 11]]
How can I reference any specific element in these arrays?
I know for a standard array such as
[a, b, c, d]
I could find b as arrayName[2]
Does such a method exist for referencing the nth element in the nth array in a multidimensional array? Also, if such a method exists, does it also apply to jagged arrays?
Upvotes: 0
Views: 1171
Reputation: 1074355
Does such a method exist for referencing the nth element in the nth array in a multidimensional array?
Yes:
arrayName[x][y]
JavaScript doesn't have multi-dimensional arrays; instead, it has arrays of arrays. So what you have in your example is an array containing references to other arrays, so arrayName[x]
gives us the reference to the array at position x
of arrayName
, then [y]
gives us the element at position y
of that array.
Also, if such a method exists, does it also apply to jagged arrays?
Yes, because there's nothing special about jagged/sparse arrays in JavaScript. JavaScript's standard arrays aren't arrays at all, in fact.
Gratuitous Live Example:
var arrayName = [[12, 23],[27,-6],[52, -32],[82, 11]];
var x = 2; // The third array in 'arrayName'
var y = 1; // The second entry in that array
console.log(arrayName[x][y]);
Upvotes: 1
Reputation: 9
We access the elements of a 2D array similarly to accessing a 1D array - by using the 0-based index value in both the row and column dimension with the array reference variable and bracket notation. Look at the example below. Here is the payScaleTable reference variable from the example in the last section of this lesson. Following the reference table are two sets of brackets. The first set of brackets contains the index of the row that is to be accessed, and the second set of brackets contains the index of the column that is to be accessed. The arrows in the figure show where the index-pair [2][1]
"points" in the 2D array. It points to the third row (index 2) and the 2nd column (index 1). Essentially identical to 1D arrays, but now you have to think in 2D tabular format.
Upvotes: 0
Reputation: 8971
Just specify a second index:
arrayName[1][1];
So, if you have arrayName = [[10, 20], [11, 25]]
, arrayName[1]
would be [11, 25]
and arrayName[1][1]
would be 25
Upvotes: 1