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

4
  • 2
    "Or can i just do..." Just try it and see for yourself :) Commented Apr 2, 2019 at 22:52
  • var multi = [ [1,2,3], [4,5,6] ] You just have to experiment. Commented Apr 2, 2019 at 22:54
  • the cleanest way is one that everyone can understand without having headache Commented Apr 2, 2019 at 22:58
  • Possible duplicate of Creating multidimensional arrays & matrices in Javascript Commented Apr 2, 2019 at 23:09

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.