how to create a 2d array in javascript code example
Example 1: javascript define multidimensional array
var iMax = 20;
var jMax = 10;
var f = new Array();
for (i=0;i<iMax;i++) {
f[i]=new Array();
for (j=0;j<jMax;j++) {
f[i][j]=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
function twoDimensionArray(a, b) {
let arr = [];
for (let i = 0; i< a; i++) {
for(let j = 0; j< b; j++) {
arr[i] = [];
}
}
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 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);