Skip to content Skip to sidebar Skip to footer

Store Table In 2d Array Jquery

I'm trying to store a table in a 2d array so that each item in the array will be an array containing all the cells in a row. I'm using: var tRow = []; var tRows = []; tab = docume

Solution 1:

You can do this with two map() functions.

var tRows = $('tr').map(function() {
  return [$(this).find('td').map(function() {
    return $(this).text()
  }).get()]
}).get()

console.log(tRows)
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><tr><td>Row 1 cell 1</td><td>Row 1 cell 2</td><td>Row 1 cell 3</td><td>Row 1 cell 4</td></tr><tr><td>Row 2 cell 1</td><td>Row 2 cell 2</td><td>Row 2 cell 3</td><td>Row 2 cell 4</td></tr></table>

Solution 2:

Your issue is you need a new tRow array for each iteration of outer loop.

Just move var tRow = []; inside that row loop

var tRows = [];
tab = document.getElementById('table');

for (var r = 0; r < tab.rows.length; r++) {
  var tRow = [];// start new row arrayfor (var c = 0; c < tab.rows[r].cells.length; c++) {
    tRow[c] = tab.rows[r].cells[c].innerHTML;       
  }
  tRows.push(tRow);
}

console.log(tRows);
<tableid="table"><tr><td>Row 1 cell 1</td><td>Row 1 cell 2</td><td>Row 1 cell 3</td><td>Row 1 cell 4</td></tr><tr><td>Row 2 cell 1</td><td>Row 2 cell 2</td><td>Row 2 cell 3</td><td>Row 2 cell 4</td></tr></table>

Post a Comment for "Store Table In 2d Array Jquery"