Last active
April 25, 2019 07:27
-
-
Save westc/0fa021ae5e66004c60e07c967e0b747f to your computer and use it in GitHub Desktop.
Convert a table to a 2D array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test for
colSpan
androwSpan
weirdness: http://jsbin.com/worodiluki/edit?html,js,console,output