0

I have an 2D Array like this

[["Manchester City", 92], ["Liverpool", 82], ["Tottenham", 78], ["Chelsea", 78], ["Manchester United", 72], ["Arsenal", 69]]

I want to map all of the data of 2D Array into a html table, here the example of my html table code

<table id="codexpl">
    <tr>
        <th>No</th>
        <th>Club</th>
        <th>Points</th>
    </tr>
    <tr>
        <td>row 1 col 1</td>
        <td>row 1 col 2</td>
        <td>row 1 col 3 </td>
    </tr>
    <tr>
        <td>row 2 col 1</td>
        <td>row 2 col 2</td>
        <td>row 2 col 3 </td>
    </tr>
</table>

So how to solve this ? Thank you.

3 Answers 3

1

function createTable(tableData) {
  var table = document.createElement('table')
    , 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([["Manchester City", 92], ["Liverpool", 82], ["Tottenham", 78], ["Chelsea", 78], ["Manchester United", 72], ["Arsenal", 69]]
);

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

Comments

0

Loop over your array, for each top-level element, add a row to the table. Then, for each next-level element, add a cell and insert the element's contents into the table cell.

Comments

0

you can do something like this:


const toTable = (arr) =>
  `<table id="codexpl">
    <tr>
        <th>No</th>
        <th>Club</th>
        <th>Points</th>
    </tr>
    ${arr.map(
    (item, index) =>
      `<tr>
      <td>${index + 1}</td>
      <td>${item[0]}</td>
      <td>${item[1]}</td>
  </tr>`
  ).join('\n')}
</table>`

Just pass the array to it and it will return the HTML code.

Comments

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.