How to Fill a 2D Array in JavaScript?

Estimated read time 1 min read

To fill a 2D array in JavaScript, you can use nested for loops to iterate over the dimensions of the array and fill it with the desired values:

const rows = 3;
const cols = 4;
const arr = [];
for (let i = 0; i < rows; i++) {
  arr[i] = [];
  for (let j = 0; j < cols; j++) {
    arr[i][j] = 0;

This will create a 2D array filled with the value 0, with rows number of rows and cols number of columns. You can change the value in the inner loop to fill the array with any other desired values.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply