create 2d array in javascript code example

Example 1: 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 2: js initialize 2d array

let data = [];
for (let row=0; row<rows; row++) {
    data.push(new Array(cols).fill('#'));
};

Example 3: 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 4: 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 5: javascript fill 2 dimensional array

const fillSquareMatrix = (size) => {
  return Array(size)
    .fill()
    .map((u,y) => Array(size)
         .fill()
         .map((u,x) => y * size + x + 1));
};

console.log(fillSquareMatrix(3));

Example 6: creating 2d array in javascript

var [r, c] = [5, 5]; 
var m = Array(r).fill().map(()=>Array(c).fill(0));