cmdv cmdv - 7 months ago 17
Javascript Question

Creating multidimensional arrays & matrices in Javascript

Trying to create a function

mCreate()
that given a set a numbers returns a multidimensional array (matrix):

mCreate(2, 2, 2)
// [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]


When this functions handles just 2 levels of depth ie:
mCreate(2, 2) //[[0, 0], [0, 0]]
I know to do 2 levels, you can use 2 nested
for loops
but the problem I'm having is how to handle an n'th number of arguments.

Would this problem be better approached with recursion, otherwise how can I dynamically determine the number of nested
for loops
I'm going to need given the number of arguments?

ps: the most performant way would be great but not essential

EDIT - After using Benchmark.js to check perf the results were as follows:

BenLesh x 4,876,766 ops/sec ±1.12% (82 runs sampled)
Phil-P x 205,852 ops/sec ±2.01% (81 runs sampled)
Rick-H x 287,988 ops/sec ±1.25% (82 runs sampled)
Rodney-R x 97,930 ops/sec ±1.67% (81 runs sampled)
Fastest is BenLesh

Answer

One simple recursive answer is this (in ES2015):

const mCreate = (...sizes) => 
    Array.from({ length: sizes[0] }, () => 
        sizes.length === 1 ? 0 : mCreate(...sizes.slice(1)));

JS Bin here

EDIT: I think I'd add the initializer in with a higher order function though:

const mCreate = (...sizes) => (initialValue) => 
    Array.from({ length: sizes[0] }, () => 
        sizes.length === 1 ? initialValue : mCreate(...sizes.slice(1))(initialValue));

Which could be used like:

mCreate(2, 2, 2)('hi'); 
// [[["hi", "hi"], ["hi", "hi"]], [["hi", "hi"], ["hi", "hi"]]]

JSBin of that