0

What is the cleanest way of allocating a multidimentional array in javascript? Or is it even necessary? Currently I am doing it like so

let dp = new Array(8).fill(null).map(item =>(new Array(8).fill(null).map(item =>(new Array(8).fill(null))))); (for 8x8x8).

Or can i just do let dp = new Array(); dp[1][1][1] = 7? Wondering the best way to do stuff like this

2 Answers2

2

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

I would use Array.from() and pass an array of size, and a value (val) for the last arrays. Use array destructuring, and rest to get the current array length, and array of the next nested arrays. If the next array is not empty, use the result of calling the function again. If not, return the val.

const generateMulti = ([current, ...next], val) =>
  Array.from({ length: current }, () => next.length ?
    generateMulti(next, val) : val
  )

const result = generateMulti([3, 2, 2], null)

console.log(JSON.stringify(result))
Ori Drori
  • 183,571
  • 29
  • 224
  • 209