create a 2d map in javascript in javascript

One way to create a 2D map in JavaScript is by using a 2D array. We can initialize the array with the desired size and then use nested loops to populate it with the desired values.

Here's an example of creating a 2D map with a size of 5x5 and setting all values to 0:

index.tsx
const numRows = 5;
const numCols = 5;

// Create 2D array and set all values to 0
const map = [];
for (let row = 0; row < numRows; row++) {
  map[row] = [];
  for (let col = 0; col < numCols; col++) {
    map[row][col] = 0;
  }
}

// Print out the map
for (let row = 0; row < numRows; row++) {
  let line = '';
  for (let col = 0; col < numCols; col++) {
    line += map[row][col] + ' ';
  }
  console.log(line);
}
415 chars
21 lines

This will output the following map:

index.tsx
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
55 chars
6 lines

You can customize the size of the map and the values that are set by changing the numRows and numCols variables and the inner loop that sets the values.

gistlibby LogSnag