how to initialize a 2d array in js code example

Example 1: js initialize 2d array

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

Example 2: javascript two dimensional array

var grid = [];
iMax = 3;
jMax = 2;
count = 0;

    for (let i = 0; i < iMax; i++) {
      grid[i] = [];

      for (let j = 0; j < jMax; j++) {
        grid[i][j] = count;
        count++;
      }
    }

// grid = [
//   [ 0, 1 ]
//   [ 2, 3 ]
//   [ 4, 5 ]
// ];

console.log(grid[0][2]); // 4

Example 3: javascript create 2d array

function create2DArray(rows, columns, value = (x, y) => 0) {
  var array = new Array(rows);
  for (var i = 0; i < rows; i++) {
    array[i] = new Array(columns);
    for (var j = 0; j < columns; j++) {
      array[i][j] = value(i, j);
    }
  }

  return array;
}

var array = create2DArray(2, 3, (row, column) => row + column);
console.log(array);
//output: [[0, 1, 2],
//         [1, 2, 3]]

Example 4: reach to each cell in 2d array javascript

// ... Matrix declaration goes here

function getCell(matrix, y, x) {
  var NO_VALUE = null;
  var value, hasValue;
  
  try {
    hasValue = matrix[y][x] !== undefined;
    value    = hasValue?  matrix[y][x] : NO_VALUE;
  } catch(e) {
    value    = NO_VALUE;
  }

  return value;
}

function surroundings(matrix, y, x) {
  // Directions are clockwise
  return {
    up:        getCell(matrix, y-1, x),
    upRight:   getCell(matrix, y-1, x+1),
    right:     getCell(matrix, y,   x+1),
    downRight: getCell(matrix, y+1, x+1),
    down:      getCell(matrix, y+1, x),
    downLeft:  getCell(matrix, y+1, x-1),
    left:      getCell(matrix, y,   x-1),
    upLeft:    getCell(matrix, y-1, x-1)
  }
}