1// dynamic function to cteate table out of 2d arrays
2function createTable(element, tableData) {
3
4 // creating table elements
5 var table = document.createElement('table');
6 // creating table body <tbody> element
7 var tableBody = document.createElement('tbody');
8
9 // creating rows based on first diamention datas
10 tableData.forEach(function(rowData) {
11 var row = document.createElement('tr');
12
13 // creating cells in each row based on second diamention datas
14 rowData.forEach(function(cellData) {
15 var cell = document.createElement('td');
16 // adding array item to it's cell
17 cell.appendChild(document.createTextNode(cellData));
18 // adding the cell to it's row
19 row.appendChild(cell);
20 });
21
22 // adding each row to table body
23 tableBody.appendChild(row);
24 });
25
26 // adding table body to table
27 table.appendChild(tableBody);
28 // adding table to document body
29 element.appendChild(table);
30}
31
32// example
33createTable(
34 document.getElementById('my-table'),
35 [
36 ['r1, c1', ' r1, c2'],
37 ['r2, c1', ' r2, c2']
38 ]
39);
40