How to create a two dimensional (2D) array dynamically with random rows and cols in JavaScript

1 Answer

0 votes
const rows = Math.floor(Math.random() * 9) + 1;
const cols = Math.floor(Math.random() * 7);
 
let count = 1;
let array = [];

for (let i = 0; i < rows; i++) {
  	let data = [];
  	for (let j = 0; j < cols; j++) {
    	data.push("value" + count);
    	count++;
  	}
  	array.push(data);
}

console.log(array);
   
   
     
     
/*
run:
     
[["value1", "value2", "value3", "value4"], 
 ["value5", "value6", "value7", "value8"], 
 ["value9", "value10", "value11", "value12"], 
 ["value13", "value14", "value15", "value16"]]
     
*/

 



answered Jan 25, 2022 by avibootz
edited Jan 25, 2022 by avibootz
...