denvaar denvaar - 4 years ago 147
Javascript Question

Generate 2d array with Javascript/es6

Is there a more functional way to create a 2d array in Javascript than what I have here? Perhaps using

.apply
?

generatePuzzle(size) {
let puzzle = [];
for (let i = 0; i < size; i++) {
puzzle[i] = [];
for (let j = 0; j < size; j++) {
puzzle[i][j] = Math.floor((Math.random() * 200) + 1);
}
}
return puzzle;
}


For instance, in python, you can do something like
[[0]*4]*4
to create a 4x4 list

Answer Source
const repeat = (fn, n) => Array(n).fill(0).map(fn);
const rand = () => Math.floor((Math.random() * 200) + 1);
const puzzle = n => repeat(() => repeat(rand, n), n);

And then puzzle(3), eg, will return a 3x3 matrix filled with random numbers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download