1

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 = document.getElementById('table'); 

for(var r = 0 ; r < tab.rows.length ; r++) {
    for (var c=0; c < tab.rows[r].cells.length; c++){
        tRow[c] = tab.rows[r].cells[c].innerHTML;                       
    }

    tRows.push(tRow);
}

this just gives me the last row item in 20 places rather than each item in the table at its respective index. So, for this 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>

tRows will be:

tRows =[ [Row 2 cell 1,Row 2 cell 2,Row 2 cell 3,Row 2 cell 4] , [Row 2 cell 1,Row 2 cell 2,Row 2 cell 3,Row 2 cell 4] ]

instead of:

tRows =[ [Row 1 cell 1,Row 1 cell 2,Row 1 cell 3,Row 1 cell 4] , [Row 2 cell 1,Row 2 cell 2,Row 2 cell 3,Row 2 cell 4] ]

I don't know what I'm doing wrong. Please help.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Johny Doey
  • 13
  • 4

2 Answers2

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)
<script src="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>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

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 array
  for (var c = 0; c < tab.rows[r].cells.length; c++) {
    tRow[c] = tab.rows[r].cells[c].innerHTML;       
  }
  tRows.push(tRow);
}

console.log(tRows);
<table id="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>
charlietfl
  • 170,828
  • 13
  • 121
  • 150