EN
JavaScript - create two dimensional array
3 points
In this article, we would like to show you how to create a two-dimensional array in JavaScript.
xxxxxxxxxx
1
const array = [[1, 2], [3, 4]];
2
3
console.log(array[0][0]); // 1
4
console.log(array[0][1]); // 2
5
console.log(array[1][0]); // 3
6
console.log(array[1][1]); // 4
In this example, we use Array()
constructor to dynamically create empty two-dimensional array.
xxxxxxxxxx
1
const array = new Array(2);
2
3
for (let i = 0; i < array.length; ++i) {
4
const subarray = new Array(3);
5
for (let j = 0; j < subarray.length; ++j) {
6
subarray[j] = `item-${i}-${j}`;
7
}
8
array[i] = subarray;
9
}
10
11
console.log(JSON.stringify(array, null, 4));
xxxxxxxxxx
1
const createArray1D = (size, creator = (index) => null) => {
2
const array = Array(size);
3
for (let i = 0; i < size; ++i) {
4
array[i] = creator(i);
5
}
6
return array;
7
};
8
9
const createArray2D = (width, height, creator = (i, j) => null) => {
10
return createArray1D(height, (i) => createArray1D(width, (j) => creator(i, j)));
11
}
12
13
14
// Usage example:
15
16
const array = createArray2D(2, 3, (i, j) => `item-${i}-${j}`);
17
18
console.log(JSON.stringify(array));