Skip to content

Instantly share code, notes, and snippets.

@westc
Last active April 25, 2019 07:27
Show Gist options
  • Save westc/0fa021ae5e66004c60e07c967e0b747f to your computer and use it in GitHub Desktop.
Save westc/0fa021ae5e66004c60e07c967e0b747f to your computer and use it in GitHub Desktop.
Convert a table to a 2D array.
function tableToArray(tbl, opt_cellValueGetter) {
opt_cellValueGetter = opt_cellValueGetter || function(td) { return td.textContent || td.innerText; };
var twoD = [];
for (var rowCount = tbl.rows.length, rowIndex = 0; rowIndex < rowCount; rowIndex++) {
twoD.push([]);
}
for (var rowIndex = 0, tr; rowIndex < rowCount; rowIndex++) {
var tr = tbl.rows[rowIndex];
for (var colIndex = 0, colCount = tr.cells.length, offset = 0; colIndex < colCount; colIndex++) {
var td = tr.cells[colIndex], text = opt_cellValueGetter(td, colIndex, rowIndex, tbl);
while (twoD[rowIndex].hasOwnProperty(colIndex + offset)) {
offset++;
}
for (var i = 0, colSpan = parseInt(td.colSpan, 10) || 1; i < colSpan; i++) {
for (var j = 0, rowSpan = parseInt(td.rowSpan, 10) || 1; j < rowSpan; j++) {
twoD[rowIndex + j][colIndex + offset + i] = text;
}
}
}
}
return twoD;
}
@westc
Copy link
Author

westc commented Aug 21, 2016

Test for colSpan and rowSpan weirdness: http://jsbin.com/worodiluki/edit?html,js,console,output

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment