Reputation: 29
I have an 2D Array like this
[["Manchester City", 92], ["Liverpool", 82], ["Tottenham", 78], ["Chelsea", 78], ["Manchester United", 72], ["Arsenal", 69]]
I want to map all of the data of 2D Array into a html table, here the example of my html table code
<table id="codexpl">
<tr>
<th>No</th>
<th>Club</th>
<th>Points</th>
</tr>
<tr>
<td>row 1 col 1</td>
<td>row 1 col 2</td>
<td>row 1 col 3 </td>
</tr>
<tr>
<td>row 2 col 1</td>
<td>row 2 col 2</td>
<td>row 2 col 3 </td>
</tr>
</table>
So how to solve this ? Thank you.
Upvotes: 0
Views: 1039
Reputation: 872
function createTable(tableData) {
var table = document.createElement('table')
, 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([["Manchester City", 92], ["Liverpool", 82], ["Tottenham", 78], ["Chelsea", 78], ["Manchester United", 72], ["Arsenal", 69]]
);
Upvotes: 1
Reputation: 374
you can do something like this:
const toTable = (arr) =>
`<table id="codexpl">
<tr>
<th>No</th>
<th>Club</th>
<th>Points</th>
</tr>
${arr.map(
(item, index) =>
`<tr>
<td>${index + 1}</td>
<td>${item[0]}</td>
<td>${item[1]}</td>
</tr>`
).join('\n')}
</table>`
Just pass the array to it and it will return the HTML code.
Upvotes: 0
Reputation: 1389
Loop over your array, for each top-level element, add a row to the table. Then, for each next-level element, add a cell and insert the element's contents into the table cell.
Upvotes: 0