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"]]);
Answer from bmavity on Stack Overflow
🌐
Medium
medium.com › wdstack › quick-blurb-generating-a-table-from-an-array-in-javascript-41386fd449a9
Quick Blurb: Generating a Table from an Array in JavaScript | by Zak Frisch | WDstack | Medium
January 24, 2017 - //setup our table array var tableArr = [ ["row 1, cell 1", "row 1, cell 2"], ["row 2, cell 1", "row 2, cell 2"] ]//create a Table Object let table = document.createElement('table');//iterate over every array(row) within tableArr for (let row of tableArr) {//Insert a new row element into the table element table.insertRow();//Iterate over every index(cell) in each array(row) for (let cell of row) {//While iterating over the index(cell) //insert a cell into the table element let newCell = table.rows[table.rows.length - 1].insertCell();//add text to the created cell element newCell.textContent = cell; } }//append the compiled table to the DOM document.body.appendChild(table);
Discussions

algorithm - Generate an HTML table using JavaScript from an array of objects - Code Review Stack Exchange
I've an array of objects and I want to convert it into a visual table in HTML; so I did it last night, but I was tired. I don't think it is the right way of doing it, even though it's working and g... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
June 2, 2022
How to create a table from an array using javascript - Stack Overflow
Stack Data Licensing Data licensing offering for businesses to build and improve AI tools and models ... Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ... I am trying to figure out how I can transfer an array with multiple variables into an HTML table using only javascript... More on stackoverflow.com
🌐 stackoverflow.com
html - Convert table to array in JavaScript without using jQuery - Stack Overflow
I need to convert the table grid i created into an multidimensional array according to the content inside the table. Array would be in format like: var array = [ [column,column,...... More on stackoverflow.com
🌐 stackoverflow.com
Print out Javascript array in table - Stack Overflow
A reusable JSON to table conversion solution for objects in an array type of data structure. Object properties are inserted at the header cells and the values are inserted at the data cells. More on stackoverflow.com
🌐 stackoverflow.com
June 12, 2016
🌐
Code Boxx
code-boxx.com › home › 2 ways to create table from array in javascript
2 Ways To Create Table From Array In Javascript
January 11, 2024 - This beginner's tutorial will show how to create table from array in Javascript using 2 different methods. Example code download included.
🌐
Codecademy
codecademy.com › forum_questions › 53c596f68c1ccca727000600
JavaScript array vs HTML table - demonstration | Codecademy
To re-iterate, this program takes a JavaScript array and tabulates it as best it can under HTML constraints. That’s all it is doing. Nothing fancy when it comes down to it. I hope every learner can come back to this for sake of further learning and experimentation. Experimentation is the first (and perhaps most important) attribute in a curious programmer’s repertoire. ... Continuing with the direct approach, we now have a count of the empty cells in the HTML table.
🌐
GitHub
gist.github.com › WickyNilliams › 9252235
parseTable.js - convert HTML table to array of objects. MIT licensed (https://opensource.org/licenses/MIT) · GitHub
parseTable.js - convert HTML table to array of objects. MIT licensed (https://opensource.org/licenses/MIT) - index.html
Top answer
1 of 4
8

Use the DOM APIs

For performance avoid adding markup (HTML) to the page via JavaScript. The DOM APIs are much faster and can be abstracted to make more readable code (DOM APIs are very verbose).

Source complexity

Your solution is convoluted and hard to read. It looks like you tackled the whole problem in one big step. More than a dozen lines of code should be seen as more than one problem to solve.

To solve complex or multi step problem break them into smaller single role parts.

  • Find all rows names

  • Find all columns names

  • Find value by row column name

  • Create DOM elements

  • Append a DOM elements

  • Create a table.

Each of these sub problems can then be solved by defining a function. When you have all the functions you can solve the main problem by combining the sub problems.

Try to make the functions generic. Property names should be dynamic so that you need only minor changes when the data changes. The example show 4 tables, to change your code to provide the different tables would take a lot more work than adding 3 more calls to the main function.

Example

The rewrite breaks the problem into the pars described above. The title, and the names of the row and column properties are passed to the function.

You can see the flexibility of this approach as the table can easily be rotated and transformed by changing the argument order and properties to use for columns and rows.

const notes = [{note: "n1", subject: "subject1", value: 10 }, {note: "n2", subject: "subject2", value: 15 }, {note: "n2", subject: "subject2", value: 5 }, {note: "n3", subject: "subject2", value: 20 }];

const tag    = (tagName, props = {}) => Object.assign(document.createElement(tagName), props);
const txtTag = (tagName, str, props = {}) => tag(tagName, {textContent: str, ...props});
const append = (el, ...sibs) => sibs.reduce((p, sib) => (p.appendChild(sib), p), el);

append(document.body, 
  createTable("Subjects", "note", "subject", "value", notes),
  createTable("Notes", "subject", "note", "value", notes),
  createTable("Notes", "value", "note", "value", notes),
  createTable("Values", "subject", "value", "value", notes));

function createTable(title, colKey, rowKey, valKey, data) {
  const byKey = key => [...new Set(data.map(rec => rec[key]))];
  const byRowCol = (row, col) => data.reduce((val, rec) => 
    val + (rec[rowKey] === row && rec[colKey] === col ? rec[valKey] : 0), 0);
  const rows = byKey(rowKey), cols = byKey(colKey);
  return append(tag("table"),
    append(tag("tbody"),
      append(tag("tr"),
        txtTag("th", title),
        ...cols.map(str => txtTag("th", str))
      ),
      ...rows.map(row => 
        append(tag("tr"),
          txtTag("th", row),
          ...cols.map(col => txtTag("td", byRowCol(row, col)))
        )
      )
    )
  )
}
* {font-family: arial}
table, tr, th, td {
  border-collapse: collapse;
  border: 1px solid;
  padding: 3px 10px;
  margin: 4px;
}

2 of 4
4

A short review;

  • JS should be lowerCamelCase, so make_matrix -> makeMatrix
  • array_objs should probably be just be objects
  • I am not a big fan of HTML in JS, consider using a template
  • In makeMatrix you both convert the data into a new structure and build the output, I would split this across 2 functions
  • I see a tendency to name variables more after what they are than what they contain, I hope my counter-examples shows what I mean
  • I find your code very dense and hard to read
  • However I really like the trick to create subjects and notes, will steal that ;)

let notes = [
  { note: "n1", subject: "subject1", value: 10 },
  { note: "n2", subject: "subject2", value: 15 },
  { note: "n2", subject: "subject2", value: 5 },
  { note: "n3", subject: "subject2", value: 20 },
];

function restructureSubjectScores(subjectScores){
  const out = {};
  for(const score of subjectScores){
    out[score.subject] = out[score.subject] || {};
    out[score.subject][score.note] = score.value;
  }
  return out;
}

function buildTable(noteScores){
  const subjects = [...new Set(noteScores.map(({ subject }) => subject))];
  const notes = [...new Set(noteScores.map(({ note }) => note))];
  
  const tableData = restructureSubjectScores(noteScores);  
  const table = document.getElementById('tableTemplate').content.firstElementChild.cloneNode(true);
  
  const header = table.querySelector('thead tr');
  header.innerHTML += notes.map(column => `<th>${column}</th>`).join("");
  
  const tbody = table.querySelector("tbody");
  const rowTemplate = document.getElementById('rowTemplate').content.firstElementChild;

  for(const subject of subjects){
    const row = rowTemplate.cloneNode(true);
    row.querySelector("th").textContent = subject;

    for(const note of notes){
      row.innerHTML += `<td>${tableData[subject][note] || 0}</td>`;
    }
    tbody.appendChild(row);
  }
  return table;
}

document.querySelector(".content").appendChild(buildTable(notes));
table {
  border-collapse: collapse;
  border: 1px solid;
}
tr,
th,
td {
  border: 1px solid;
  padding: 3px 10px;
}
<div class="content"></div>
<template id="tableTemplate">
<table>
  <thead><tr>
    <th class="subject">Subjects</th>
  </tr></thead>
  <tbody>
  </tbody>
</table>
</template>

<template id="rowTemplate">
  <tr>
    <th class="subject"></th>
  </tr>
</template>

🌐
Code.mu
code.mu › en › javascript › book › prime › dom › practice › table-creating-via-objects-array
Creating an HTML table from an array of objects in JavaScript
This approach gives great flexibility - we ourselves can regulate the order of the data in the table cells (we can, for example, swap the first and last names). In addition, if desired, we can hang events on certain cells. For example, you can attach some kind of action on click to the cell with the last name, and so on. ... let employees = [ {name: 'employee1', age: 30, salary: 400}, {name: 'employee2', age: 31, salary: 500}, {name: 'employee3', age: 32, salary: 600}, ]; Output this array elements as an HTML table.
Find elsewhere
Top answer
1 of 4
5

You're currently trying to add a string to an table object. Check this page out.

function createTable() {

    var headers = ["Title", "Author", "Read?"];
    var table = document.createElement("TABLE");  //makes a table element for the page
        
    for(var i = 0; i < books.length; i++) {
        var row = table.insertRow(i);
        row.insertCell(0).innerHTML = books[i].title;
        row.insertCell(1).innerHTML = books[i].author;
        row.insertCell(2).innerHTML = books[i].alreadyRead;
    }

    var header = table.createTHead();
    var headerRow = header.insertRow(0);
    for(var i = 0; i < headers.length; i++) {
        headerRow.insertCell(i).innerHTML = headers[i];
    }

    document.body.append(table);
}
2 of 4
1

To add stringified tags to parent tag,

parentTag.innerHTML = stringifiedTag;

Hope it's helpful.

  var books = [
    {
        title: 'The Stranger',
        author: 'Albert Camus',
        alreadyRead: true
    },
    {
        title: 'Binging with Babish',
        author: 'Andrew Rea',
        alreadyRead: true
    },
    {
        title: 'You Suck at Cooking: The Absurdly Practical Guide to Sucking Slightly Less at Making Food: A Cookbook',
        author: 'You Suck at Cooking',
        alreadyRead: false
    }];

createTable();

function createTable() {
    var table = document.createElement("table");  //makes a table element for the page
    let innerT = "";
    
    innerT += "<tr class='firstRow'><th>Title</th><th>Author</th><th>Read?</th></tr>";  //adds the first row that contains the sections for the table

    for (var i = 0; i < books.length; i++)  //loops through the array 
    {
        //add info from the array into this
        innerT += "<tr><td>" + books[i].title + "</td><td>";
    }
    table.innerHTML = innerT;
    
    document.body.append(table);
}

🌐
Observable
observablehq.com › @aaronkyle › simple-html-table-from-js-array
Simple HTML Table from JS Array / Aaron Kyle Dennis | Observable
February 2, 2019 - This notebook demonstrates how to generate a simple HTML table from array data. Thanks to Fabian Iwand for carrying it over the finish line! The example used here is derives from Danny Goodman's JavaScript & DHTML Cookbook: Solutions & Examples for Web Programmers, can be accessed via Google ...
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-create-an-html-table-from-an-object-array-using-javascript
How to Create an HTML Table from an Object Array Using JavaScript ? | GeeksforGeeks
April 28, 2025 - To build an HTML table using ReactJS from arrays we can use the array methods to iterate to iterate the elements and create the table rows Prerequisites:NPM & Node.jsReact JSJavaScript Array.map()HTML TableApproach: To build an HTML table from ...
🌐
GitHub
gist.github.com › mapsi › 8939976
Convert JS array to HTML table · GitHub
Convert JS array to HTML table. GitHub Gist: instantly share code, notes, and snippets.
🌐
Linux Hint
linuxhint.com › create-table-from-array-objects-javascript
How to Create Table From an Array of Objects in JavaScript
October 9, 2022 - To create a table from an array of objects in JavaScript, you can use the “HTML table string” or “map()” method in your JavaScript program.
🌐
Blogger
1bestcsharp.blogspot.com › 2017 › 03 › javascript-populate-html-table-from-array.html
Javascript - Populate HTML Table From Array - C#, JAVA,PHP, Programming ,Source Code
<!DOCTYPE html> <html> <head> <title> Add Rows To HTML Table From Array </title> <meta charset="windows-1252"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <table id="table" border="1"> <!-- The Row Number 0 --> <tr> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr> <!-- End Row Number 0 --> <!-- <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> --> </table> <script> var array = [["A1","B1","C
🌐
javaspring
javaspring.net › blog › create-html-table-from-javascript-object
How to Create an HTML Table from a JavaScript Object Array (with Auto-Incrementing ID, Name & Relevance Columns) for Beginners — javaspring.net
In this tutorial, we’ll walk through creating a dynamic HTML table from a JavaScript object array. We’ll include auto-incrementing IDs (to uniquely identify each row), Name, and Relevance columns. By the end, you’ll understand how to dynamically generate tables, manipulate the DOM, and style your table for readability—no prior advanced JavaScript experience required! ... Basic knowledge of HTML (e.g., tags, elements, and the DOM).
🌐
Valentino G.
valentinog.com › blog › html-table
Back To The Basics: How To Generate a Table With JavaScript
February 2, 2020 - In this tutorial we saw how to generate a table with JavaScript. An HTML table is represented in the DOM by the HTMLTableElement. This interface exposes a lot of useful methods for manipulating table heads with createTHead and table rows with insertRow. HTML table rows on the other hand inherit from HTMLTableRowElement. This interface has two methods, one of the most important being insertCell. Given an array of objects it is possible to iterate over them with a for...of loop for generating table rows.
🌐
TutorialsPoint
tutorialspoint.com › convert-html-table-to-array-in-javascript
Convert HTML table to array in JavaScript?
Get data from tag using find() and store that data into array using push(). Let’s say the following is our table − <table id="details"> <thead> <tr>
🌐
SitePoint
sitepoint.com › javascript
JavaScript array displaying on a Html Table - JavaScript - SitePoint Forums | Web Development & Design Community
April 19, 2020 - Here I have the javascript to display that a student is in grade 3. I need to put the entire array (gradeYears) onto a HTML table and keep my loop going. I need to highlight the grade that the student would be in on the table. I seem to be able to find the information to take an array and put ...
Top answer
1 of 3
1

I've interpreted your question as though you want to extract 1 zone from voting_section, that zone should have the highest number appended to it.

var data = [{
      "votes": 200,
      "invalid_votes": 140,
      "valid_votes": 60,
      "voting_section": {
        "level": 1,
        "zone1": "US",
        "zone2": "Delaware"
      }
    },
    {
      "votes": 300,
      "invalid_votes": 40,
      "valid_votes": 260,
      "voting_section": {
        "level": 1,
        "zone1": "US",
        "zone2": "California",
        "zone3": "Los Angeles"
      }
    }
  ],
  html = "";

function getLastZone(voting_section) {
  var highestZone = {
    zoneNumber: null,
    zoneText: null
  };
  for (var zone in voting_section) {
    var checkZone = /zone(\d)/g.exec(zone);
    if (checkZone) {
      if (parseInt(checkZone[1]) > highestZone.zoneNumber) {
        highestZone = {
          zoneNumber: [checkZone[1]],
          zoneText: voting_section[zone]
        };
      }
    }
  }
  return highestZone.zoneText;
}

data.forEach(function(e, i) {
  html += "<tr>" + "<td>" + getLastZone(e.voting_section) + "</td>" + 
                   "<td>" + e.votes + "</td>" + 
                   "<td>" + e.valid_votes + "</td>" + 
                   "<td>" + e.invalid_votes + "</td>" + "</tr>";
})

document.getElementById("putHere").innerHTML = html;
table {
  border-collapse: collapse;
  border-left: 1px solid #bbbbbb;
  border-top: 1px solid #bbbbbb;
}
th, td {
  border-right: 1px solid #bbbbbb;
  border-bottom: 1px solid #bbbbbb;
}
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>Document</title>

</head>

<body>
  <table>
    <thead>
      <th>Zone</th>
      <th>Votes</th>
      <th>Valid Votes</th>
      <th>Invalid Votes</th>
    </thead>
    <tbody id="putHere"></tbody>
  </table>
</body>

</html>

2 of 3
0

You could create one main function to build the table, from which you could call a row-building function (while iterating over the data rows). I've added an example to my post here.

var data = [{
  "votes":200,
  "invalid_votes":140,
  "valid_votes":60,
  "voting_section":{"level":2, "zone1":"US", "zone2":"Delaware"}
},
{
  "votes":300,
  "invalid_votes":40,
  "valid_votes":260,
  "voting_section":{"level":3, "zone1":"US", "zone2":"California", "zone3":"Los Angeles"}
}];

var buildTable = function(data, container){
  /* Builds one data row into a <tr> element string */
  var buildRow = function(rowData){
    return `<tr><td>${rowData.voting_section.zone2}</td><td>${rowData.votes}</td><td>${rowData.valid_votes}</td><td>${rowData.invalid_votes}</td></tr>`;
  }
  
  /* Reduces the array of row data into one string */
  var rows = data.reduce(function(rows, row){
    return rows+buildRow(row);
  }, '');
  
  /* Creates the full table and includes the rows string */
  container.innerHTML = `<table><thead><tr><td></td><td>Votes</td><td>Valid Votes</td><td>Invalid Votes</td></tr></thead><tbody>${rows}</tbody>`;
}

var resultsTableDiv = document.getElementById('results')
buildTable(data, resultsTableDiv);
<div id="results"></div>