How can I create a two dimensional array in JavaScript?
Solution 1:
var 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);
Solution 2:
You simply make each item within the array an array.
var x = new Array(10);
for (var i = 0; i < x.length; i++) {
x[i] = new Array(3);
}
console.log(x);
Solution 3:
Similar to activa's answer, here's a function to create an n-dimensional array:
function createArray(length) {
var arr = new Array(length || 0),
i = length;
if (arguments.length > 1) {
var args = Array.prototype.slice.call(arguments, 1);
while(i--) arr[length-1 - i] = createArray.apply(this, args);
}
return arr;
}
createArray(); // [] or new Array()
createArray(2); // new Array(2)
createArray(3, 2); // [new Array(2),
// new Array(2),
// new Array(2)]
Solution 4:
How to create an empty two dimensional array (one-line)
Array.from(Array(2), () => new Array(4))
2 and 4 being first and second dimensions respectively.
We are making use of Array.from
, which can take an array-like param and an optional mapping for each of the elements.
Array.from(arrayLike[, mapFn[, thisArg]])
var arr = Array.from(Array(2), () => new Array(4));
arr[0][0] = 'foo';
console.info(arr);
The same trick can be used to Create a JavaScript array containing 1...N
Alternatively (but more inefficient 12% with n = 10,000
)
Array(2).fill(null).map(() => Array(4))
The performance decrease comes with the fact that we have to have the first dimension values initialized to run .map
. Remember that Array
will not allocate the positions until you order it to through .fill
or direct value assignment.
var arr = Array(2).fill(null).map(() => Array(4));
arr[0][0] = 'foo';
console.info(arr);
Follow up
Here's a method that appears correct, but has issues.
Array(2).fill(Array(4)); // BAD! Rows are copied by reference
While it does return the apparently desired two dimensional array ([ [ <4 empty items> ], [ <4 empty items> ] ]
), there a catch: first dimension arrays have been copied by reference. That means a arr[0][0] = 'foo'
would actually change two rows instead of one.
var arr = Array(2).fill(Array(4));
arr[0][0] = 'foo';
console.info(arr);
console.info(arr[0][0], arr[1][0]);
Solution 5:
Javascript only has 1-dimensional arrays, but you can build arrays of arrays, as others pointed out.
The following function can be used to construct a 2-d array of fixed dimensions:
function Create2DArray(rows) {
var arr = [];
for (var i=0;i<rows;i++) {
arr[i] = [];
}
return arr;
}
The number of columns is not really important, because it is not required to specify the size of an array before using it.
Then you can just call:
var arr = Create2DArray(100);
arr[50][2] = 5;
arr[70][5] = 7454;
// ...