javascrip 2D array code example
Example 1: 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 2: creating 2d array in javascript
var [r, c] = [5, 5];
var m = Array(r).fill().map(()=>Array(c).fill(0));