2d array in js code example

Example 1: how to make a 2d array in js

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

Example 2: js array two dimensional

// declaration of a two-dimensional array
// 5 is the number of rows and 4 is the number of columns.
const matrix = new Array(5).fill(0).map(() => new Array(4).fill(0));

console.log(matrix[0][0]); // 0

Example 3: how to read 2 dimensional array in javascript

activities.forEach((activity) => {
    activity.forEach((data) => {
        console.log(data);
    });
});

Example 4: creating a 2d array in js

var x = new Array(10);

for (var i = 0; i < x.length; i++) {
  x[i] = new Array(3);
}

console.log(x);

Example 5: how to create 2d array in javascript

// program to create a two dimensional array

function twoDimensionArray(a, b) {
    let arr = [];

    // creating two dimensional array
    for (let i = 0; i< a; i++) {
        for(let j = 0; j< b; j++) {
            arr[i] = [];
        }
    }

    // inserting elements to array
    for (let i = 0; i< a; i++) {
        for(let j = 0; j< b; j++) {
            arr[i][j] = j;
        }
    }
    return arr;
}

const x = 2;
const y = 3;

const result = twoDimensionArray(x, y);
console.log(result);

Example 6: multi-dimensional array js

var array = [
  ["0, 0", "1, 0", "2, 0", "3, 0", "4, 0"],
  ["0, 1", "1, 1", "2, 1", "3, 1", "4, 1"],
  ["0, 2", "1, 2", "2, 2", "3, 2", "4, 2"],
  ["0, 3", "1, 3", "2, 3", "3, 3", "4, 3"],
  ["0, 4", "1, 4", "2, 4", "3, 4", "4, 4"],
  ]; // Think of it as coordinates, array[x, y] x = 0; y = 0; is "0, 0" on 
	// this grid

console.log(array[3][3]); // returns "3, 3"
// If you use graphics (ex: p5js or JS Canvas) then this will be a 5x5 map.
// Useful for roguelikes and/or raycasters.