Generate HTML table from 2D JavaScript array
Solution 1:
Here's a function that will use the dom instead of string concatenation.
function createTable(tableData) {
var table = document.createElement('table');
var tableBody = document.createElement('tbody');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
document.body.appendChild(table);
}
createTable([["row 1, cell 1", "row 1, cell 2"], ["row 2, cell 1", "row 2, cell 2"]]);
Solution 2:
This is pretty easy to do with a double for loop.
function makeTableHTML(myArray) {
var result = "<table border=1>";
for(var i=0; i<myArray.length; i++) {
result += "<tr>";
for(var j=0; j<myArray[i].length; j++){
result += "<td>"+myArray[i][j]+"</td>";
}
result += "</tr>";
}
result += "</table>";
return result;
}
Solution 3:
Another innerHTML-less version.
function makeTable(array) {
var table = document.createElement('table');
for (var i = 0; i < array.length; i++) {
var row = document.createElement('tr');
for (var j = 0; j < array[i].length; j++) {
var cell = document.createElement('td');
cell.textContent = array[i][j];
row.appendChild(cell);
}
table.appendChild(row);
}
return table;
}