-2

How to create 2D array in js without looping?

Wanna get something like this:

[
    [number, number, number],
    [number, number, number], 
    [number, number, number],
]
1
  • What is your intended output? Commented Jan 12, 2021 at 10:38

2 Answers 2

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))

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.