⊗jsPmMuAF 173 of 502 menu

Filling multidimensional arrays in JavaScript

Suppose now we want to create some multidimensional array with numbers in a loop. For example, here is a two-dimensional array:

[[1, 2, 3], [1, 2, 3], [1, 2, 3]]

Let's solve the problem by using two nested loops. The outer loop will create sub-arrays and the inner loop will fill these sub-arrays with numbers:

let arr = []; for (let i = 0; i < 3; i++) { arr[i] = []; // create a subarray for (let j = 0; j < 3; j++) { arr[i].push(j + 1); // fill the subarray with numbers } } console.log(arr);

Form the following array using two nested loops:

[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]

Form the following array using two nested loops:

[ ['x', 'x', 'x', 'x'], ['x', 'x', 'x', 'x'], ['x', 'x', 'x', 'x'] ]

Form the following array using three nested loops:

[ [ [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], ], [ [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], ], [ [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], ], ]
enru