Categories
JavaScript Answers

How to generate HTML table from a 2D JavaScript array?

Spread the love

Sometimes, we want to generate HTML table from a 2D JavaScript array.

In this article, we’ll look at how to generate HTML table from a 2D JavaScript array.

How to generate HTML table from a 2D JavaScript array?

To generate HTML table from a 2D JavaScript array, we can use the insertRow and insertCell methods.

For instance, we write

const createTable = (tableData) => {
  const table = document.createElement("table");
  let row = {};
  let cell = {};

  tableData.forEach((rowData) => {
    row = table.insertRow(-1);
    rowData.forEach((cellData) => {
      cell = row.insertCell();
      cell.textContent = cellData;
    });
  });
  document.body.appendChild(table);
};

to create a table with createElement.

Then we loop through the tableData array with forEach.

In it the callback, we call insertRow to insert a tr element.

Then we loop through the rowData with forEach and call insertCell to insert a td.

Then we set its textContent to cellData.

Finally, we call appendChild to append the table to the body element.

Conclusion

To generate HTML table from a 2D JavaScript array, we can use the insertRow and insertCell methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *