Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create dynamic html table using javascript from simple array

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.

like image 559
Alexander Hörl Avatar asked May 01 '18 09:05

Alexander Hörl


2 Answers

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>
like image 153
Nina Scholz Avatar answered Oct 21 '22 10:10

Nina Scholz


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

like image 42
Taylor Rahul Avatar answered Oct 21 '22 08:10

Taylor Rahul