-2

How to create 2D array in js without looping?

Wanna get something like this:

[
    [number, number, number],
    [number, number, number], 
    [number, number, number],
]
viverte
  • 43
  • 7

2 Answers2

1

You can use nested map()

const randomNum = (min, max) => {
    return Math.trunc(Math.random() * (max - min)) + min;
}
const createRandom2DArray = (rows, columns) => [...Array(rows)].map(x => [...Array(columns)].map(x => randomNum(1,5)));

console.log(createRandom2DArray(5,5))
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0
const randomTable = (rows, cols) => Array.from(
  {length: rows}, 
  () => Array.from({length: cols}, () => Math.floor(Math.random() * 5))
)

console.table(randomTable(10, 5)) // browser console only, not StackOverflow's

source: stackoverflow

Gal Birka
  • 581
  • 6
  • 16