Display a 2 dimensional array in html as a grid

Display a 2 dimensional array in html as a grid
0

#1

I have the following array in my javascript file:

[[0,0,0],
[0,0,0],
[0,1,0]]

and I want it to be displayed somewhat like this in js:
snip

It’s important that the table adapts to the array, so if I have

[[0,1,0,0],
[0,0,0,0],
[0,1,0,0]]

it should have one more row. Do I need to type out the table by hand or can I do something like a for loop that adds a square for every item in the array?


#3

Hey, I’ve written you some code to handle this. This should work for any array as long as you keep them in same format.

https://jsfiddle.net/q746zeLj/1/

It can be added the way you style any element via javascript, I’ve added the style to the paragraph so you can check it via the inspect tool to see that it works.

Now, remember that grid-template-areas must be made of different areas, none of which can be repeated (that’s why I went with letters instead of your format). The only thing that can be repeated are dots " . " and they signalize that the specific grid should be empty, so you could potentially replace all the zeros with dots if you want them empty.
There are some ways to override this and use the same names repeatedly but that’s more advanced so you’d need to look into it yourself.

// edit
Now I’ve noticed you want to work with tables, not CSS Grid haha, but still, maybe it’ll give you some inspiration to how to apply this to a table.


#4

If you need to dynamically change the representation of an array on a page, the easiest way i see is to use js to manipulate grid-template-columns and grid-template-rows of a display: grid container.


#5

It’s quite easy to do actually with table instead of grid:

array.forEach(row => {
  createTableRow();
  row.forEach(item => createTableCell(item ? 'red' : 'transparent'));
};

It’s not an actual code, but you can get the idea I believe.