One possibility is to create a makeArr
function which recursively calls itself, to which you can pass a nested object indicating the length and values desired, something like this:
const makeArr = (length, item) => Array.from(
{ length },
() => typeof item === 'object' ? makeArr(item.length, item.item) : item
);
const arrx3x3 = makeArr(3, { length: 3, item: { length: 3, item: 0 } });
// check that every array is a separate reference:
arrx3x3[0][0][0] = 1;
console.log(arrx3x3);
This will allow for relatively clean creation of arbitrary array dimensions.
If every nested array will have the same length, then you just need to indicate the length
on the first parameter to makeArr
:
const makeArr = (length, item) => Array.from(
{ length },
() => typeof item === 'object' ? makeArr(length, item.item) : item
);
const arrx3x3 = makeArr(3, { item: { item: 0 } });
// check that every array is a separate reference:
arrx3x3[0][0][0] = 1;
console.log(arrx3x3);
If you want to fill the nested array items with non-array objects (eg where the 0
is now, in the nested item : 0
), you'll have to change the typeof item === 'object'
test to something more precise.