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

5
  • Can you post the tableData? Commented Nov 25, 2016 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]] Commented Nov 25, 2016 at 17:53
  • That's not valid array data. Is all that data supposed to be strings? Commented Nov 25, 2016 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"]] Commented Nov 25, 2016 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"], ...]? Commented Nov 25, 2016 at 18:00

4 Answers 4

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; }

Sign up to request clarification or add additional context in comments.

3 Comments

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 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?
Yes, that's exactly what I mean
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);

Comments

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);
  
}

Comments

-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;
}

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.