M W M W - 6 months ago 13
Javascript Question

Specific Array Element in Multidimensional Array

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?

Answer

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
snippet.log(arrayName[x][y]);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Comments