Search code examples
javascripthtml-table

Generate HTML table from 2D JavaScript array


In JavaScript, is it possible to generate an HTML table from a 2D array? The syntax for writing HTML tables tends to be very verbose, so I want to generate an HTML table from a 2D JavaScript array, as shown:

[
  ["row 1, cell 1", "row 1, cell 2"], 
  ["row 2, cell 1", "row 2, cell 2"]
]

would become:

<table border="1">
  <tr>
    <td>row 1, cell 1</td>
    <td>row 1, cell 2</td>
  </tr>
  <tr>
    <td>row 2, cell 1</td>
    <td>row 2, cell 2</td>
  </tr>
</table>

So I'm trying to write a JavaScript function that would return a table from a 2D JavaScript array, as shown:

function getTable(array){
  // take a 2D JavaScript string array as input, and return an HTML table.
}

Solution

  • Here's a function that will use the dom instead of string concatenation.

    function createTable(tableData) {
      var table = document.createElement('table');
      var tableBody = document.createElement('tbody');
    
      tableData.forEach(function(rowData) {
        var row = document.createElement('tr');
    
        rowData.forEach(function(cellData) {
          var cell = document.createElement('td');
          cell.appendChild(document.createTextNode(cellData));
          row.appendChild(cell);
        });
    
        tableBody.appendChild(row);
      });
    
      table.appendChild(tableBody);
      document.body.appendChild(table);
    }
    
    createTable([["row 1, cell 1", "row 1, cell 2"], ["row 2, cell 1", "row 2, cell 2"]]);