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 dec
The reason some say that it isn't possible is because a two dimensional array is really just an array of arrays. The other comments here provide perfectly valid methods of creating two dimensional arrays in JavaScript, but the purest point of view would be that you have a one dimensional array of objects, each of those objects would be a one dimensional array consisting of two elements.
So, that's the cause of the conflicting view points.
Two-liner:
var a = [];
while(a.push([]) < 10);
It will generate an array a of the length 10, filled with arrays. (Push adds an element to an array and returns the new length)
Javascript does not support two dimensional arrays, instead we store an array inside another array and fetch the data from that array depending on what position of that array you want to access. Remember array numeration starts at ZERO.
Code Example:
/* Two dimensional array that's 5 x 5
C0 C1 C2 C3 C4
R0[1][1][1][1][1]
R1[1][1][1][1][1]
R2[1][1][1][1][1]
R3[1][1][1][1][1]
R4[1][1][1][1][1]
*/
var row0 = [1,1,1,1,1],
row1 = [1,1,1,1,1],
row2 = [1,1,1,1,1],
row3 = [1,1,1,1,1],
row4 = [1,1,1,1,1];
var table = [row0,row1,row2,row3,row4];
console.log(table[0][0]); // Get the first item in the array
Array(m).fill(v).map(() => Array(n).fill(v))
You can create a 2 Dimensional array m x n
with initial value m
and n
can be any numbers v
can be any value string
, number
, undefined
.
One approach can be var a = [m][n]
Two dimensional arrays are created the same way single dimensional arrays are. And you access them like array[0][1]
.
var arr = [1, 2, [3, 4], 5];
alert (arr[2][1]); //alerts "4"
My approach is very similar to @Bineesh answer but with a more general approach.
You can declare the double array as follows:
var myDoubleArray = [[]];
And the storing and accessing the contents in the following manner:
var testArray1 = [9,8]
var testArray2 = [3,5,7,9,10]
var testArray3 = {"test":123}
var index = 0;
myDoubleArray[index++] = testArray1;
myDoubleArray[index++] = testArray2;
myDoubleArray[index++] = testArray3;
console.log(myDoubleArray[0],myDoubleArray[1][3], myDoubleArray[2]['test'],)
This will print the expected output
[ 9, 8 ] 9 123