I want to define a function that will create a nested array that is n-levels deep with n-elements in each level-1 array.
So, for example, the code below works for 2 levels:
function genMatrix() {
const matrix = [];
let total = 0;
for(let i=0; i<2; i++) {
matrix[i] = [];
for(let j=0; j<2; j++) {
total++;
matrix[i][j] = total;
}
}
return matrix;
}
This will output the following: [ [ 1, 2 ], [ 3, 4 ] ]
I know that I can extend this same idea by simply adding more nested loops. But I want a function that will generate a similar array of any level.
Something like this:
function genMatrix(levels) {... return matrix}
I was trying to do this recursively, but I didn't get very far :(
So how could I write a recursive function that creates an array of any depth in a similar way to the example above?
n=3would give[[[1,2,3],[4,5,6]]]?