Convert html table to array in javascript

How can an HTML table be converted into a JavaScript array?

<table id="cartGrid">
          <th>Item Description</th>
          <th>Unit Price</th>
          <th>Ext Price</th>
    <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>

Here’s one example of doing what you want.

var myTableArray = [];

$("table#cartGrid tr").each(function() {
    var arrayOfThisRow = [];
    var tableData = $(this).find('td');
    if (tableData.length > 0) {
        tableData.each(function() { arrayOfThisRow.push($(this).text()); });


You could probably expand on this, say, using the text of the TH to instead create a key-value pair for each TD.

Since this implementation uses a multidimensional array, you can access a row and a td by doing something like this:

myTableArray[1][3] // Fourth td of the second tablerow

Edit: Here’s a fiddle for your example:

This a function coverts an Html Table (just give the id) and it returns an array of the table :

            function table_to_array(table_id) {
                    myData = document.getElementById(table_id).rows
                    my_liste = []
                    for (var i = 0; i < myData.length; i++) {
                            el = myData[i].children
                            my_el = []
                            for (var j = 0; j < el.length; j++) {

                    return my_liste

I hope it helps you !

You can write also with key value pair. this is so simple.

function htmlTableDataToArrayOfObject(){

    var arrayOfThisRow = [];
            $("#cartGrid tbody tr").each(function() {
                var description = $(this).find('td:eq(0)').text();
                var qty = $(this).find('td:eq(1)').text();
                var unitPrice= $(this).find('td:eq(2)').text();
                         desc: description,
                         quantity: qty,
                         price: unitPrice

Here’s typescript solution:

function getTableContent(table: HTMLTableElement): string[][] {
    return Array.from(table.rows).reduce((acc, row) => {
        const columns = Array.from(row.children)
            .map(column => column.textContent || '')

        return acc.concat(columns);
    }, [] as string[][])

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   How can i conditionally apply title in angular js

Similar Posts