How to convert an HTML table to an array in JavaScript?

Sometimes, we want to convert an HTML table to an array in JavaScript.

In this article, we’ll look at how to convert an HTML table to an array in JavaScript.

How to convert an HTML table to an array in JavaScript?

To convert an HTML table to an array in JavaScript, we can use the spread operator and some array methods.

For instance, we add a table with:

<table id="cartGrid">
  <thead>
    <tr>
      <th>Item Description</th>
      <th>Qty</th>
      <th>Unit Price</th>
      <th>Ext Price</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Old Lamp</td>
      <td>1</td>
      <td>107.00</td>
      <td>107.00</td>
    <tr>
      <td>Blue POst</td>
      <td>2</td>
      <td>7.00</td>
      <td>14.00</td>
  </tbody>
</table>

Then we write:

const table = document.querySelector('table')
const arr = [...table.rows].map(r => [...r.querySelectorAll('td, th')].map(td => td.textContent))
console.log(arr)

to get all the tr elements in a node list with table.rows.

Then we spread them into an array.

Next, we call map with a callback that select all the td’s or th’s, spread them into an array, and then call map on them to get their textContent.

As a result, arr is:

[
  [
    "Item Description",
    "Qty",
    "Unit Price",
    "Ext Price"
  ],
  [
    "Old Lamp",
    "1",
    "107.00",
    "107.00"
  ],
  [
    "Blue POst",
    "2",
    "7.00",
    "14.00"
  ]
]

Conclusion

To convert an HTML table to an array in JavaScript, we can use the spread operator and some array methods.