javascript 2d arrays 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: 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 3: 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 4: 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 5: how to make a 4 dimensional array in JavaScript

/*having the previous array easy to make is very useful*/

function Array2D(x, y){
 let arr = Array(x);
  for(let i = 0; i < y; i++){
   arr[i] = Array(y);
  }
  return arr;
}

function Array3D(x, y, z){
 let arr = Array2D(x, y);
      for(let i = 0; i < y; i++){
       for(let j = 0; j < z; j++){
        arr[i][j] = Array(z);
       }
      }
  return arr;
}

function Array4D(x, y, z, w){
 let arr = Array3D(x, y, z);
      for(let i = 0; i < x; i++){
       for(let j = 0; j < y; j++){
        for(let n = 0; n < z; n++){
        arr[i][j][n] = Array(w);
       }
       }
      }
  return arr;
}
/*making the array*/
let myArray = Array4D(10, 10, 10, 10);

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