Skip to content

Create new row for each value that is in an array html javascript

I have this array:

var output = [[[a], [a1, a3, a5]], [[b], [b1, b2, b3]]]

and i wish to create a table as per below in html with javascript:

a  |  b
-------
a1 | b1
a3 | b2
a5 | b3

but at the moment I’m only getting it like this:

   a     |    b
--------------------
a1,a3,a5 | b1,b2,b3

with this code

  var table = '<table ' + TABLEFORMAT + ' ">';

  for (var row = 0; row < output.length; row++) {

    table += '<tr>';

    for (var col = 0; col < output[row].length; col++) {
      if (output[row][col] === "" || 0) {
        table += '<td>' + '' + '</td>';
      } else
        if (row === 0) {
          table += '<th>' + output[col][row] + '</th>';
        } else {
         table += '<td>' + output[col][row] + '</td>';
        }
    }
    table += '</tr>';
  }

is it possible to do so?

Answer

You could transform the data to a table like structure and then create the table.

const
    pad = (array, tag) => array.map(v => `<${tag}>${v}</${tag}>`).join(''),
    raw = [[['a'], ['a1', 'a3', 'a5']], [['b'], ['b1', 'b2', 'b3']]],
    data = raw.reduce((r, [[h], a]) => {
        r.header.push(h);
        a.forEach((v, i) => (r.body[i] = r.body[i] || []).push(v));
        return r;
    }, { header: [], body: [] }),
    table = document.createElement('table');

table.innerHTML = `<table>
    <thead><tr>${pad(data.header, 'th')}</tr></thead>
    <tbody>${pad(data.body.map(a => pad(a, 'td')), 'tr')}
</tbody>`;

document.body.appendChild(table);