Generate HTML Table from 2D JavaScript Array

Generate HTML table from 2D JavaScript array

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"]]);

JavaScript 2D array to table, how to target the table to a div?

Say you had

<div id="MyTargetDiv"></div>

then you need to change

document.body.appendChild(table);

to

document.getElementById("MyTargetDiv").appendChild(table);

Create html table from two array where arrays lengths not necessary the same

The tricky thing here is that 1 array can be longer than the other, so first of all:

  1. find the largest array's size
  2. create a loop that will add as many table rows as the longest array size
  3. add the cell content to each row, handing the case that 1 array might not have any defined values at that particular array index (because different size arrays)

I've added // 1. // 2. and // 3. to help reference the explaination.

const a1 = ['a','b','c']
const a2 = ['d','e','f','g']

const maxArrayLength = Math.max(a1.length, a2.length) // 1.

const tbody = document.querySelector('tbody');

for (let i = 0; i < maxArrayLength; i++) { // 2.
const tr = tbody.insertRow(); // 2.
tr.insertCell().innerHTML = a1[i] ? a1[i] : '' // 3.
tr.insertCell().innerHTML = a2[i] ? a2[i] : '' // 3.
}
<table>
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Generate html table content with JavaScript array

You can loop over to the array and create a HTML string with <tr> and <td> then apply those to the inner HTML of the table element:

var array = [['name1', 'material1', 'number1', 'place1', 'country1'],['name2', 'material2', 'number2', 'place2', 'country2']];var nHTML = document.querySelector('table').innerHTML;array.forEach(function(arrItem){  var td = '<tr>';  arrItem.forEach(function(item){    td += '<td>'+item+'</td>' ;  });  nHTML += td + '</tr>';});document.querySelector('table').innerHTML = nHTML;
<table border='1'>    <tr>        <th>Name</th>        <th>Material</th>        <th>Number</th>        <th>Place</th>        <th>Country</th>    </tr></table>

How to create vertical html table from 2d array using javascript

In this answer, I've created an object from your arrays and then made the table from the object:

createTable([               ["Person A", "Person B", "Person C", "Person D"],                ["Wed Jun 29 12:30", "Thu Jun 30 13:45", "Thu Jun 30 13:46"," Fri Jul 1 15:40"]            ]); 
function createTable(tableData) { // Get ready to store the data in an Object var obj = {}; var len = tableData[0].length; // Map Array1 elements as properties and Array2 elements as values for(var i = 0; i < len; ++i){ obj[tableData[0][i]] = tableData[1][i]; } console.log(obj);
var table = document.createElement('table'); // Create the table element table.setAttribute("id", "table"); // Give the table an id attribute var tableBody = document.createElement('tbody'); // Create the tbody element
// Loop over the object, rather than the original arrays: for(var prop in obj) { // Loop through the nested arrays var row = document.createElement('tr'); // Create a row for each nested array var cell = document.createElement('td'); // Make a cell for each element cell.appendChild(document.createTextNode(prop)); // Add the element's data to the cell row.appendChild(cell); // Add the cell to the row cell = document.createElement('td'); // Make a cell for each element cell.appendChild(document.createTextNode(obj[prop])); // Add the element's data to the cell row.appendChild(cell); // Add the cell to the row
tableBody.appendChild(row); // Add the row to the tbody }
table.appendChild(tableBody); // Add the tbody to the table document.body.appendChild(table); // Add the table to the page.}
#table, #table td  {border: 1px solid black; }

Make a table using array data in Javascript

Maybe something like that

function populate() {
var table = "";
for (var i in data) {
table += "<td>" +
data[i].name + "</td>" +
"<td>" + data[i].id + "</td>";
table += "</tr>";
document.getElementById("#selectdiv").innerHTML = table;
}
}

Creating html table from multidimensional javascript array

You shouldn't append content like this to your table, because the browser must redraw the whole DOM, so it's not very efficient.

You should build your table inside a string, then append the whole string to your table, like this :

$('#tb').ready(     
function() {
console.log('table loaded');

var ar = Array(2);

for(var i=0;i<ar.length;i++){
ar[i]=Array(2);
}

ar[0][0]='1';
ar[1][0]='2';
ar[0][1]='3';
ar[1][1]='4';

console.log('multidimensional array created!');
//Prepare the outputed string
var theTable = "";
for(var j=0;j<ar.length;j++){
theTable += '<tr>';
for(var k=0;k<2;k++){
theTable += '<td>'+ar[k][j]+'</td>';
}
theTable += '</tr>';
}
//Finally appended the whole string to the table
$('#tb').append(theTable);
//expected:
//12
//34
//actual
//1 2 3 4
});

I've made a Jsfiddle for you : JSFiddle

Have fun !



Related Topics



Leave a reply



Submit