HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How can I create a two dimensional array in JavaScript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arrayhowdimensionalcantwojavascriptcreate

Problem

I have been reading online and some places say it isn't possible, some say it is and then give an example and others refute the example, etc.

-
How do I declare a 2 dimensional array in JavaScript? (assuming it's possible)

-
How would I access its members? (myArray[0][1] or myArray[0,1]?)

Solution

Practically? Yes. You can create an array of arrays which functions as an 2D array as every item is an array itself:


let items = [
[1, 2],
[3, 4],
[5, 6]
];
console.log(items[0][0]); // 1
console.log(items[0][1]); // 2
console.log(items[1][0]); // 3
console.log(items[1][1]); // 4
console.log(items);




But technically this is just an array of arrays and not a “true” 2D array, as I. J. Kennedy pointed out.

It should be noted that you could keep nesting arrays into one another and so create “multidimensional” arrays.

Context

Stack Overflow Q#966225, score: 1429

Revisions (0)

No revisions yet.