Is there any better way to create a multidimensional array in Javascript

In C++, creating a 2D array is really simple

int two_d[n][m];

But after I google how to achieve the same function in javascript, it seems much more complex.

  • Array.from() method*
let arr = Array.from(Array(m), () => new Array(n));
  • Array.prototype.map()Method*
let arr = Array(m).fill().map(() => Array(n));

Does Javascript support a similar syntax like C++ which will be much simpler and more visible?

Nope.

I am confused why JS doesn't support simple syntax like C++. You know, when we want to create a multidimensional array in JS, the above ways will become very long and ugly. Maybe I should go to post a proposal for it?

JS doesn't have mutlidimensional arrays - it only has "arrays of arrays". I'm not sure why there's no simple syntax to create them, but I've not found them commonly used in my experience to warrant syntax. Maybe others have a different perspective.

In my opinion, it is because arrays in JavaScript are extendible, while they should be allocated a specified capacity in C/C++ first. So in many cases, we don't need to specify the capacity firstly in JavaScript, except in one case, where we need to iterate a list of natural numbers (0, 1, 2, ...) :

const times = n => Array(n).fill('');
times(10).forEach(console.log); // => 0, 1, 2, 3, ...

I might not be up to date on the latest JS engine heuristics here but Iā€™m sure at one point it was actually sometimes slower to pre-allocate arrays in JS because the arrays then have the wrong internal type compared to what was actually going to be stored.

So in that way better to treat them more like c++ vectors and let them naturally grow their backing storage.

3 Likes

It's still faster in V8 at least for non-immediate arrays, but yeah, the performance gap isn't nearly large enough IMHO to merit adding multi-dimensional arrays through dedicated syntax, not when they're already relatively straightforward to code in userland.