2

I am taking creating a html table using data from a function that returns a 2d array, but need help making the table go vertically instead of horizontally. Right now, I followed the steps from the answers in this stack overflow question but am having trouble completely understanding the code so that I can fix it for my use case.

Here is the html code as I have it now:

/**
  * Adds an html table
  */ 
  function createTable(inputData) {
  //Checks for error - if so, does not output table
  if (inputData == "ERROR") {
    document.getElementById('errorMessage').innerHTML = "Error: Unable to find sport";
  } else {
  var tableData = JSON.parse(inputData);
  var table = document.createElement('table');
    table.setAttribute("id", "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);
    }
  }

How can I change this to make the table go vertically instead of horizontally? If possible, I want don't want to change how the table is created (it is being embedded in a google script, which I asked about before).

Edit: The tableData is: [["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"]]

Community
  • 1
  • 1
Grant
  • 131
  • 1
  • 2
  • 12
  • Can you post the `tableData`? – Scott Marcus Nov 25 '16 at 17:50
  • Yes: `[[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]]` – Grant Nov 25 '16 at 17:53
  • That's not valid array data. Is all that data supposed to be strings? – Scott Marcus Nov 25 '16 at 17:55
  • My bad. Yes, they are all strings: `[["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"]]` – Grant Nov 25 '16 at 17:57
  • Can you change the function which gives you that array so that you get `[["Person A", "Wed Jun 29 12:30"], ["Person B", "Thu Jun 30 13:45"], ...]`? – Andrew Morton Nov 25 '16 at 18:00

4 Answers4

2

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; }
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • Is it possible to have the columns/row "stack" - so that it goes `"Person A" "Wed Jun 29..."` and then `"Person B" "Thu Jun..." **below** it rather than beside it? – Grant Nov 25 '16 at 18:07
  • @Grant Explain what you mean by "stack". Do you mean reverse the rows/columns so that `Person A`, `Person B`, etc. runs vertical and the dates are beside them? – Scott Marcus Nov 25 '16 at 18:09
  • Yes, that's exactly what I mean – Grant Nov 25 '16 at 18:10
1

Try this one. And the working fiddle.

data = '[["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(inputData) {
  //Checks for error - if so, does not output table
  if (inputData == "ERROR") {
    document.getElementById('errorMessage').innerHTML = "Error: Unable to find sport";
  } else {
    var tableData = JSON.parse(inputData);
    var table = document.createElement('table');
    table.setAttribute("id", "table");
    var tableBody = document.createElement('tbody');
    var rows = [];
    // use the first element in the array to build table rows
    header = tableData.pop(0);
    header.forEach(function(headerData) {
        var row = document.createElement('tr');
        var cell = document.createElement('td');
        cell.appendChild(document.createTextNode(headerData));
        row.appendChild(cell);
        rows[rows.length] = row;
    });
    // now go through the rest to update the rows array
    tableData.forEach(function(rowData) {
        var numRow = 0;
        rowData.forEach(function(cellData) {
            var cell = document.createElement('td');
            cell.appendChild(document.createTextNode(cellData));
            rows[numRow].insertBefore(cell, rows[numRow].firstChild);
            ++numRow;
        });
    });
    // now append those childs to the tableBody
    rows.forEach(function(row) {
        tableBody.appendChild(row);
    });
    table.appendChild(tableBody);
    document.body.appendChild(table);
  }
}

createTable(data);
arhak
  • 2,488
  • 1
  • 24
  • 38
Marc Compte
  • 4,579
  • 2
  • 16
  • 22
0

Here's a simple easily readable function to create a table from a 2d array.

var 
data = [
  ["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"]
];

createTable(data);

function createTable(inputData)
{
  
  var table = document.createElement("table");
  var r,c;
  
  for (var row in inputData[0]) {
    // create row
    r = table.insertRow(row);
    // create col 1
    c = r.insertCell(0);
    c.innerHTML = inputData[0][row];
    // create col 2
    c = r.insertCell(1);
    c.innerHTML = inputData[1][row];
  }
  
  document.body.appendChild(table);
  
}
Stubbies
  • 3,054
  • 1
  • 24
  • 33
-1

Simply cycle through the array and apply the correct dimension. Sort of like this:

 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;
}
Dean.DePue
  • 1,013
  • 1
  • 21
  • 45
  • What would I need to do to make this create the table? I need the createTable function to actually create the table rather than return it. – Grant Nov 25 '16 at 18:00