how to make a 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: js initialize 2d array

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

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: creating 2d array in javascript

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

Example 6: 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]]

Tags:

Java Example