Generating multidimensional arrays in JavaScript

I needed to do this recently so I thought I would share my solution.

Create a 2D 3x3 Array

1
Array(3).fill().map(a => Array(3))

Going deeper requires additional nesting. Here is a 3x3x3

1
2
3
4
5
6
7
8
9
Array(3)
.fill()
.map(a => {
return Array(3)
.fill()
.map(a => {
return Array(3)
})
})

With a bit of meta programming we can write a function that takes an Array describing our required xD array layout and generates it for us.

1
2
3
4
5
6
7
8
f = arr => {
let str = 'return ', l = arr.length;
arr.forEach((v, i) => {
str += i < l-1 ? `Array(${v}).fill().map(a => ` : `Array(${v}` + ')'.repeat(l);
});
return Function(str)();
}
f([4,5,6]) // Generates a 4x5x6 Array

Oh yea, careful using the Function constructor to create a new function, security and all that.