Javascript technique for creating tables from arrays of comma-separated strings

I am attempting to generate an HTML table using a given input string that is separated by commas

// HeaderTable = Headers Table  
// DataTable   = Body Table 

Input Values:

headerTable =  "Header1,Header2,Header3"
dataTable   =  [["TEST1,TEST1,TEST1"],["TEST2,TEST2,TEST2"],["TEST3,TEST3,TEST3"]]

Expected response:

<table>
  <thead>
    <tr>
      <th>Header 1</th>
      <th>Header 2</th>
      <th>Header 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>TEST1</td>
      <td>TEST2</td>
      <td>TEST3</td>
    </tr>
    <tr>
      <td>TEST1</td>
      <td>TEST2</td>
      <td>TEST3</td>       
    </tr>
    <tr>
      <td>TEST1</td>
      <td>TEST2</td>
      <td>TEST3</td> 
    </tr>
  </tbody>
</table>

Get back a unique html table code as a string

Desired response format Format Image

My Implementation Jsfiddle

Answer №1

Give this a shot:

<div id="container"></div>

let dataList = ["TEST1", "TEST2", "TEST3"]
let headerList = [" Header 1", "Header 2", "Header 3"]

let container = document.getElementById('container');

let thead = document.createElement('thead');
let th = document.createElement('th');
let tbody = document.createElement('tbody');
let td = document.createElement('td');
let tr = document.createElement('tr');
container.appendChild(tr);

container.appendChild(thead);
thead.appendChild(tr);

for(let i = 0; i < headerList.length; i++){
    th = document.createElement('th');
    th.textContent = headerList[i];
    tr.appendChild(th);
}

container.appendChild(tbody);
tbody.appendChild(tr);

for(let i = 0; i < dataList.length; i++){
    td = document.createElement('td');
    td.textContent = dataList[i];
    tr.appendChild(td);
}

Answer №2

Right here:

function generateTable(headers, data) {
    let table = document.createElement("table");
    let headerList = headers;
    let dataList = data;

    var thead = document.createElement("thead");
    table.appendChild(thead);

    var tbody = document.createElement("tbody");
    table.appendChild(tbody);

    (function () {
        var headerArray = headerList.split(", ");
        var row = document.createElement("tr");
        thead.appendChild(row);

        for (var i = 0; i < headerArray.length; i++) {
            var headerCell = document.createElement("th");
            headerCell.innerText = headerArray[i];
            row.appendChild(headerCell);
        }
    })();

    (function () {
        var dataArray = [];
        for (var i = 0; i < dataList.length; i++) {
            dataArray.push(dataList[i].split(", "));
        }

        var longestRow = dataArray.reduce((a, b) => (a.length > b.length ? a : b), []);
        for (var i = 0; i < longestRow.length; i++) {
            var row = document.createElement("tr");
            tbody.appendChild(row);
        }

        var rows = tbody.childNodes;

        for (var i = 0; i < dataArray.length; i++) {
            for (var x = 0; x < dataArray[i].length; x++) {
                var cell = document.createElement("td");
                cell.innerText = dataArray[i][x];
                rows[x].appendChild(cell);
            }
        }

        for (var i = 0; i < rows.length; i++) {
            for (var x = 0; x < rows[i].childNodes.length; x++) {
                if (rows[i].childNodes.length !== longestRow.length - 1) {
                    var cell = document.createElement("td");
                    rows[i].appendChild(cell);
                }
            }
        }
    })();

    return table;
}
/* --- Usage --- */

var headerList = "Header A, Header B, Header C";
var dataList = ["DATA1, DATA1, DATA1", "DATA2, DATA2"];

var finalTable = generateTable(headerList, dataList);
document.body.appendChild(finalTable);

This function will create a table with the specified headers and data, which you can then insert into the DOM using .appendChild(table).

It is recommended to use nested arrays instead of strings for better structure and organization.

Answer №3

Solution

function createHtmlTable(headers, bodyData) {
  var headersArray = headers.split(",");
  var tableHtml = "<table>";
  var tableHeader = "<thead><tr>";
  var tableBody = "<tbody>";
  var dataArray = [];
  var orderArray = [];
  var responseArray = [];
  const bodyDataLength = bodyData[0][0].split(",").length;

  // Create Table Header
  headersArray.forEach((header) => {
    tableHeader += "<th>" + header + "</th>";
  });

  // Create Order Array
  for (var i = 0; i < bodyDataLength; i++) {
    orderArray = [];
    bodyData.forEach((bodyElement) => {
      bodyElement.forEach((internalBodyElement) => {
        dataArray = internalBodyElement.split(",");
        dataArray.forEach((element, key) => {
          if (key == i) {
            orderArray.push(element);
          }
        });
      });
    });
    responseArray.push(orderArray);
  }

  // Create Table Body
  responseArray.forEach((dataList) => {
    tableBody += "<tr>";

    dataList.forEach((element) => {
      tableBody += "<td>" + element + "</td>";
    });

    tableBody += "</tr>";
  });

  tableHtml =
    "<table>" +
    tableHeader +
    "</tr></thead>" +
    tableBody +
    "</tbody>" +
    "</table>";
  return tableHtml;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular2 and ES6 Promise in JavaScript - tackling the issue of undefined variables

I am working with an array of objects like the one shown below: let PAGES = [ new BasePage( 'home', 'test') ]; let pagesPromise = Promise.resolve(PAGES); My goal is to retrieve a BasePage object by calling the following met ...

Update a specific division

Looking for suggestions on how to automatically refresh a div? I'm currently developing a chess game and I need the div to reload every time one player updates data in the database. The game is almost complete, but there's an issue where Player ...

Having trouble with Sequelize Single Instance not functioning properly after using Module.exports?

Here is my Sequelize Code snippet for database connection: var sequelize = new Sequelize('db-name', 'user', 'pwd', { host: 'XXX.XX.XX.XXX', dialect: 'mysql', pool: { max: 50, m ...

Updating language settings on-the-fly in a Vue application does not automatically refresh the translated content displayed on the website

My Vue app is quite large, built with Vuetify, and I recently integrated vue-i18n into it. The json translation files are set up correctly, and the $t() calls work fine in my components and other .js files. However, I'm struggling to change the locale ...

Developing a Javascript widget feature

I have a concern regarding the functionality of Javascript widgets. The widget I'm working on embeds content onto a page without using iframes, which has been effective so far. However, there are instances where certain user layouts cause the widget t ...

When using MongoDB/Mongoose, a comment can be pushed into an array upon saving. Within the array, each comment is accompanied by its respective date

I am working with a mongoose model that defines a client's schema. Here is the code snippet: const clientSchema = mongoose.Schema({ Created: { type: String }, kundnr: { type: String, unique: true, required: true }, namn: { type ...

Tips on adding an array value to the XPath syntax while conducting a search in Selenium IDE

As a novice in Selenium, I might not be articulating my query clearly. I am working with Selenium IDE version 3.17.0 and attempting to validate the presence of device names on a web page under test. These device names are stored in an array: execute scrip ...

Error in JSON parsing: Unexpected token 'u' at the beginning of the input in Angular2

I attempted to create a server using dummy data. Below is the System.js Config I have implemented (given that my routing is slightly different, this setup has been working well so far) System.config({ // baseURL to node_modules b ...

Using AngularJS Material's mdDialog to show locally stored data in a template

In the controller, the section responsible for spawning mdDialog appears as follows: $scope.removeAttendee = function(item) { console.log(item); $mdDialog.show({ controller: DialogController, templateUrl: 'views/removeMsg.tm ...

Creating a connection between my .html and .ejs files: A step-by-step guide

I have successfully created a pair of HTML files - index.html & contact.html. Within these files, I have implemented a navigation bar that allows for seamless transition between them. Recently, I delved into the realm of retrieving APIs and crafted an app ...

Tips for displaying a specific array in react JS using the map function

Hello everyone, I am currently working on creating a hotel webpage using React.js and I'm focusing on developing the facilities page. My goal is to display the description of the facilities based on the button that the user clicks. How can I achieve t ...

Applying a CSS class (or style) dynamically depending on the variable with the help of a directive

I'm facing a situation where I need to apply ng-style (or ng-class) multiple times depending on a variable. However, this repetitive task of writing ng-class for the same functionality for each widget is quite cumbersome for me. Is there a way to si ...

What is the best way to transfer attributes from a stateful component to an event handler within a Higher Order Component that encloses a child component?

My current project involves using a framework that requires passing an event handler into a Higher Order Component (HOC) which wraps one of the children of my stateful Page component. <Page> <HOC onClick={fn}> <PageColumn> ...

Index similar to JavaScript-Meadow

Is there a way to create a table of contents like the ones seen on sites such as JavaScript Gardens? How do they determine which section is currently active and are there any recommended JavaScript libraries that can help achieve this functionality? Edit: ...

Vue.js compatibility issue with SelectBoxIt jq plugin causing malfunction

On a page with numerous dynamically generated select boxes, I am looking to incorporate the jQuery selectBoxIt plugin from . Using Vue js, where is the best placement for the following code snippet to connect the plugin with the select elements? $('. ...

ReactJS rendering Express data as numbers instead of JSON format

My challenge involves sending strings from my Express server as a JSON object and then displaying these objects in my React app. Currently, instead of showing the expected data, it's simply displaying numbers for each of the 25 elements: 01234567891 ...

Angular Material's md-checkbox is a required component

I am working on a form that consists of checkboxes representing the days of the week. When the user hits submit without selecting any checkboxes, I want an error message to appear. Here is the HTML code snippet that I have: <form id="addEditForm" nam ...

Issues encountered while attempting to convert a class component to a functional component in React

I am attempting to transform my class Component into a functional component but encountering difficulties. The issue lies within this line previousLocation = this.props.location; How can I replace that in the functional component? class App extends Com ...

What could be causing my RestFul API built with express and nodejs to crash every day?

I am facing an issue with my RESTful API built using Express and Node.js. The API crashes every time it runs. I have a function that updates the date in the URL to the current datetime. I suspect that this constant update might be causing the API to crash ...

Latest Information Regarding Mongodb Aggregate Operations

Struggling to toggle a boolean value within an object that is part of a subdocument in an array. Finding it difficult to update a specific object within the array. Document: "_id" : ObjectId("54afaabd88694dc019d3b628") "Invitation" : [ { "__ ...