Haii
I want a function (pure javascript) (no jQuery) that creates multi-dimensional arrays.
I've made one that is completely hard-coded, and that limit the number of dimensions which I can dive deep.
function nestTriArray(first, second, third){
const arr = new Array(first);
for(let i=0; i<first; i++){
arr[i] = new Array(second);
for(let j=0; j<second; j++){
arr[i][j] = new Array(third);
}
}
return arr;
}
const test = nestTriArray(3,2,3);
console.log(test);
Outputs the CORRECT result:
//[[[undefined, undefined, undefined], [undefined, undefined, undefined]], [[undefined, undefined, undefined], [undefined, undefined, undefined]], [[undefined, undefined, undefined], [undefined, undefined, undefined]]]
I had another attempt to try and make it multi-dimensional in one function (rather than hard-coding a standalone function for fourth-dimension, fifth-dimension...) where I pass to the function an array, the length of the array is the number of dimensions, and each element represents the length of each sub-array. It uses a recursive function. And it outputs wrong.
That's the try:
function nestArray(conf_array/*first, second, third*/){
conf_array = [1].concat(conf_array);
const arr = [];
let last_in_ref = arr;
function re(index){
last_in_ref[conf_array[index]] = new Array(conf_array[index+1]);
for(let i=0; i<conf_array[index]; i++){
last_in_ref[i] = new Array(conf_array[index+1]);
}
last_in_ref = last_in_ref[index];
console.log(arr);
index++;
if(index < conf_array.length){re(index);}
}
re(0);
return arr;
}
const test = nestArray([3,2,3]);
console.log(test);
Outputs WRONG:
//[[[undefined, undefined], [[undefined, undefined, undefined], [undefined, undefined, undefined], [[undefined], [undefined], [undefined], [undefined]]], [undefined, undefined], [undefined, undefined]], [undefined, undefined, undefined]]
Thanks in advance!!