You can either use the Array.prototype.forEach
method, or a simple for loop. You just have to step throught each component of your bidimensional array and create a <td>
element inside your table.
By the way, I don't feel comfortable with the assumption that the table already has got the right number of rows and columns (i.e. the update
array fits the dimensions of the table): it's better to re-build the <tbody>
from scratch to avoid any error and create a more flexible function. So let's assume an initial situation like this:
<table>
<tbody id="your-table-body-id">
<!-- whatever... -->
</tbody>
</table>
Old school for
loops
Here's an example with simple for
loops:
function updateTableHTML(myArray) {
var tableBody = document.getElementById("your-table-body-id"),
newRow, newCell;
// Reset the table
tableBody.innerHTML = "";
// Build the new table
for (var i=0; i < myArray.length; i++) {
newRow = document.createElement("tr");
tableBody.appendChild(newRow);
if (myArray[i] instanceof Array) {
for (var j=0; j < myArray[i].length; j++) {
newCell = document.createElement("td");
newCell.textContent = update[i][j];
newRow.appendChild(newCell);
}
} else {
newCell = document.createElement("td");
newCell.textContent = myArray[i];
newRow.appendChild(newCell);
}
}
}
Fancy Array
methods
And here's an example with the Array.prototype.forEach
method:
function updateTableHTML(myArray) {
var tableBody = document.getElementById("your-table-body-id");
// Reset the table
tableBody.innerHTML = "";
// Build the new table
myArray.forEach(function(row) {
var newRow = document.createElement("tr");
tableBody.appendChild(newRow);
if (row instanceof Array) {
row.forEach(function(cell) {
var newCell = document.createElement("td");
newCell.textContent = cell;
newRow.appendChild(newCell);
});
} else {
newCell = document.createElement("td");
newCell.textContent = row;
newRow.appendChild(newCell);
}
});
}
Notes
Be aware that the Array.prototype.forEach
method may not be supported in every browser (i.e. Internet Explorer < 9). The for
method looks easier and more comprehensible to me (although I'm not sure which one is faster), but that's your choice.
Also, in case you were wondering: I'm checking if (row instanceof Array)
because in a situation like the following:
update = ["a", "b", "c"];
I am assuming you want a result like this:
a
b
c
and therefore you'll have to check if the value is an array before looping again and building the cells of each row.