2 Ways To Create Table From Array In Javascript

Welcome to a beginner’s tutorial on how to create a table from an array with Javascript. Need to display an array of data in a “nice HTML table”?

Creating a table from an array is as easy as looping through the array, and generating the HTML:

  1. Manually create the HTML string.
    • var table = "<table><tr>";
    • for (var VAL of ARRAY) { table += `<td>VAL</td>`; }
    • table += "</tr></table>";
    • document.getElementById("ID").innerHTML = table;
  2. Create a table, insert the rows and cells.
    • var table = document.createElement("table");
    • var row = table.insertRow();
    • for (var VAL of ARRAY) { let cell = row.insertCell(); cell.innerHTML = VAL; }
    • document.getElementById("ID").appendChild(table);

Yes, it’s that simple. But let us walk through an actual example – Read on!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Click here to download | Example on CodePen

The example code is released under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

 

JAVASCRIPT ARRAY TO HTML TABLE

All right, let us now get into the examples of turning an array into a table in Javascript.

 

TUTORIAL VIDEO

 

METHOD 1) HTML TABLE STRING

1-html-string.html
<!-- (A) EMPTY TABLE -->
<table id="demo"></table>

<script>
// (B) ARRAY OF DATA
var data = ["Alpaca", "Birb", "Cate", "Doge", "Eagle", "Foxe"];

// (C) CREATE TABLE ROWS & CELLS
var table = "<tr>",
    perrow = 2, cells = 0;
 
data.forEach((value, i) => {
  // (C1) ADD CELL
  table += `<td>${value}</td>`;
 
  // (C2) CLICK ON CELL TO DO SOMETHING
  // table += `<td onclick="alert(${i})">${value}</td>`;
 
  // (C3) BREAK INTO NEXT ROW
  cells++;
  if (cells%perrow==0 && cells!=data.length) { table += "</tr><tr>"; }
});
table += "</tr>";
 
// (D) ATTACH TO EMPTY TABLE
document.getElementById("demo").innerHTML = table;
</script>

Yep, “converting” an array to a table is as easy as that.

  1. First, all we need for the HTML is an empty <table>.
  2. Captain Obvious to the rescue, an array of data.
  3. Next, we loop through the array to generate the rows and cells <tr><td>. Yes, HTML is essentially just text, and all we need is to append all the data into HTML cells – <td>${DATA}</td>.
  4. Finally, we put the complete HTML string into the empty table, and that’s all to it!

 

 

METHOD 2) CREATE TABLE ELEMENT

2-create-element.html
<!-- (A) EMPTY TABLE -->
<table id="demo"></table>
 
<script>
// (B) ARRAY OF DATA
var data = ["Alpaca", "Birb", "Cate", "Doge", "Eagle", "Foxe"];

// (C) CREATE TABLE ROWS & CELLS
var table = document.getElementById("demo"),
    row = table.insertRow(), cell,
    perrow = 2, cells = 0;
 
data.forEach((value, i) => {
  // (C1) ADD CELL
  cell = row.insertCell();
  cell.innerHTML = value;
 
  // (C2) CLICK ON CELL TO DO SOMETHING
  // cell.onclick = () => alert(i);
 
  // (C3) BREAK INTO NEXT ROW
  cells++;
  if (cells%perrow==0 && cells!=data.length) { row = table.insertRow(); }
});
</script>

Yep, this is the “alternate” way to generate an HTML table. The basic mechanics of looping through an array remain, but we now create the table with HTML objects:

  • Get the empty HTML table – table = document.getElementById("demo");
  • Add a new row to the table – row = table.insertRow();
  • Add cells to the row – cell = row.insertCell();
  • Append data to the cell – cell.innerHTML = DATA;

You guys who are used to OOP should be very comfortable with this.

 

 

EXTRAS

That’s all for the code, and here is a small summary and some bits that may be useful to you.

 

INFOGRAPHIC CHEATSHEET

Javascript Array To HTML Table (Click To Enlarge)

 

WHICH ONE SHOULD WE USE?

Well, both the “string” and “object” methods work nicely. But some flaming troll master code ninjas will probably kick up a huge fuss and insist that we must do it the object-oriented way – As it looks more “advanced” and professional.

I will not argue with that and recommend it as well. The object-oriented way to create elements is just a lot cleaner, without having to write all those manual HTML tags. Still, nothing is wrong with writing HTML strings and inserting them into the container… HTML is plain text in reality.

 

COMPATIBILITY CHECKS

Yep. Some of the “convenient shorthand” is not supported in ancient browsers. Be careful when using those.

 

 

SUMMARY – DOM FUNCTIONS YOU SHOULD KNOW

Function Description Reference Link
document.getElementById(ID) Get the element for the given ID. Click Here
document.createElement(TAG) Creates a new DOM element. Click Here
ELEMENT.appendChild(OBJECT) Append the given object into the specified element. Click Here
TABLE.insertRow() Add a new row to the table. Click Here
ROW.insertCell() Add a new cell to the table row. Click Here

 

THE END

Thank you for reading, and we have come to the end of this short guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

9 thoughts on “2 Ways To Create Table From Array In Javascript”

  1. hello. that very nice. but what if my array content objects like this:
    [{1,”yoss”100,true}{2,…}{}]
    can i insert it in table? each object in one line [but each part in one cell]?
    thank you very much!
    yossi

    1. Use a double for loop.

      for (let OBJ of ARRAY) { for (let [K, V] of Object.entries(OBJ)) { ... } }

    1. So i have used the create-element.js and did add a listener, but when i click any row on my table i only console the last row, please help how do i click a row and be able to console that row and not the last one.
      Thnx

    2. Don’t quite catch your question, but I am assuming that you have a running number or id for each cell. Quite easy to implement, just add a custom data attribute to the cells:

      var count = 0;
      for (var i of data) {
        // ...
        cell.dataset.id = count;
        cell.addEventListener("click", function(){
          console.log(this.dataset.id);
        });
        count++;
      }
    3. Hey there
      Using the second script(2-create-element.js), how do you manipulate the script, such that you can refresh the table if you run the script multiple times and not to add repeated rows below the first created table.

      Thanks

Leave a Comment

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