create a 2d array in javascript

In JavaScript, you can create an array that contains other arrays, effectively making a 2D array or a multidimensional array. Here is an example code snippet that creates a 2D array of size 3x3:

index.tsx
let arr = new Array(3); // create a new array with length 3

for(let i = 0; i < arr.length; i++) {
  arr[i] = new Array(3); // create a nested array with length 3
}

// initialize the array with some values
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[1][0] = 4;
arr[1][1] = 5;
arr[1][2] = 6;
arr[2][0] = 7;
arr[2][1] = 8;
arr[2][2] = 9;

console.log(arr); // output: [[1,2,3],[4,5,6],[7,8,9]]
398 chars
19 lines

Alternatively, you can create a 2D array using nested array literals:

index.tsx
let arr = [[1,2,3],[4,5,6],[7,8,9]];
37 chars
2 lines

This creates the same 2D array as the previous example.

gistlibby LogSnag