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 a “nice array of data” in HTML?

Creating a table from an array is as easy as using a loop to run through the array, and generate the HTML:

  • var mytable = "<table><tr>";
  • for (var CELL of ARRAY) {  mytable += "<td>" + CELL + "</td>"; }
  • mytable += "</tr></table>";
  • document.getElementById("ID").innerHTML = mytable;

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

ⓘ I have included a zip file with all the example code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Array To Table Useful Bits & Links
Tutorial Video The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

JAVASCRIPT ARRAY TO HTML TABLE

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

 

METHOD 1) HTML TABLE STRING

1-html-string.html
<!-- (A) ALL WE NEED IS A <DIV> CONTAINER -->
<div id="container"></div>

<script>
// (B) DUMMY ARRAY
var data = ["doge", "cate", "birb", "doggo", "moon moon", "awkward seal"];

// (C) CREATE HTML TABLE
// (C1) HTML TABLE STRING
var myTable = "<table><tr>";

// (C2) LOOP THROUGH ARRAY & GENERATE ROWS-CELLS
var perrow = 2; // 2 CELLS PER ROW
data.forEach((value, i) => {
  // "NORMAL" CELL
  myTable += `<td>${value}</td>`;
 
  // CLICK ON CELL TO DO SOMETHING
  // myTable += `<td onclick="FUNCTION()">${value}</td>`;
 
  // TO PASS IN A RUNNING NUMBER OR PARAMETER
  // myTable += `<td onclick="FUNCTION(${i})">${value}</td>`;
 
  // BREAK INTO NEXT ROW
  var next = i + 1;
  if (next%perrow==0 && next!=data.length) { myTable += "</tr><tr>"; }
});

// (C3) CLOSE THE TABLE STRING
myTable += "</tr></table>";
 
// (D) ATTACH HTML TO CONTAINER
document.getElementById("container").innerHTML = myTable;
</script>

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

  1. First, all we need for the HTML is a <div> to generate the table.
  2. Captain Obvious to the rescue, an array of data.
  3. Next, we loop through the array and generate a string of HTML <table>. 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 container, and that’s all to it!

 

 

METHOD 2) CREATE TABLE ELEMENT

2-create-element.html
<!-- (A) ALL WE NEED IS A <DIV> CONTAINER -->
<div id="container"></div>
 
<script>
// (B) DUMMY ARRAY
var data = ["doge", "cate", "birb", "doggo", "moon moon", "awkward seal"];

// (C) CREATE HTML TABLE
// (C1) HTML TABLE ELEMENT
var myTable = document.createElement("table"),
    row = myTable.insertRow(), cell;

// (C2) LOOP THROUGH ARRAY & GENERATE ROWS-CELLS
var perrow = 2; // 2 CELLS PER ROW
data.forEach((value, i) => {
  // ADD CELL
  cell = row.insertCell();
  cell.innerHTML = value;
 
  // CLICK ON CELL TO DO SOMETHING
  // cell.onclick = FUNCTION;
 
  // TO PASS IN A RUNNING NUMBER OR PARAMETER
  // cell.onclick = () => { console.log(i); };
 
  // BREAK INTO NEXT ROW
  var next = i + 1;
  if (next%perrow==0 && next!=data.length) { row = myTable.insertRow(); }
});

// (D) ATTACH TABLE TO CONTAINER
document.getElementById("container").appendChild(myTable);

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

  • Create a new HTML table – myTable = document.createElement("table");
  • Add a new row to the table – row = myTable.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.

 

 

THE RESULT

 

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, there is nothing wrong with writing HTML strings and inserting them into the container… HTML is plain text in reality.

 

USEFUL BITS & LINKS

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

 

COMPATIBILITY CHECKS

Yep. Some of the “convenient shorthand” is not supported in the 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

 

TUTORIAL VIDEO

 

INFOGRAPHIC CHEAT SHEET

Create HTML Table From Javascript Array (click to enlarge)

 

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!

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

    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

      1. 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++;
        }
      2. 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 *