Create dynamic html table using javascript from simple array

15,561

Solution 1

You could iterate the array and build a new row if the remainder with 5 is zero.

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    tr;

array.forEach((v, i) => {
    var td = document.createElement('td');
    
    if (!(i % 5)) {
        tr = document.createElement('tr');
        document.getElementById('table0').appendChild(tr);
    }
    td.appendChild(document.createTextNode(v));
    tr.appendChild(td);
});
<table id="table0"></table>

Solution 2

var array = [1,2,3,4,5,6,7,8,9,10];

var result = "<table border=1>";
result += "<tr>";
for (var j = 0; j < array.length; j++) {
  result += "<td>" + array[j] + "</td>";
  if ((j + 1) % 5 == 0) {
    result += "</tr><tr>";
  }
}
result += "</tr>";
result += "</table>";

document.body.innerHTML = result;

Please give it a try if that works

Share:
15,561
Alexander Hörl
Author by

Alexander Hörl

24 y/o from 🇩🇪 ∙ Creative mind ∙ Web dev 🖥 ∙ Photography 📷 ∙ E-commerce.

Updated on June 26, 2022

Comments

  • Alexander Hörl
    Alexander Hörl almost 2 years

    I want to write some JavaScript to create a simple HTML table from an array that just contains numbers:

    var array = [1,2,3,4,5,6,7,8,9,10];
    

    The table should look like this:

    1 2 3 4 5
    6 7 8 9 10
    

    But the JavaScript code should be dynamic depending on the arrays size (always a factor of 5 though).

    I've tried a lot of stuff but it never works the way i want it to. What would be the easiest way to achieve this?

    This is one of my tries.

    var tableStart = "<table border>";
    for (i = 0; i < arraySize/5; i++){
      var tableMiddle = "<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>"
      if (arraySize/5 >= 2) {
        tableMiddle = tableMiddle + tableMiddle;
      }
    };
    var tableEnd = "</table>";
    var table = tableStart.concat(tableMiddle, tableEnd);
    

    as well as

    var result = "<table border=1>";
    for(var i=0; i<2; i++) {
        result += "<tr>";
        for(var j=0; j<array.length; j++){
            result += "<td>"+array[i]+"</td>";
        }
        result += "</tr>";
    }
    result += "</table>";
    

    this one just results in two values of the array being displayed though a lot of times.

  • Andrew Bone
    Andrew Bone about 6 years
    (1 % 5 === 0) will always be false