I know this site is a great resource that offers methods of sorting a HTML table by coding the sort and element swap myself. I use that, and it works fine. My goal is to NOT add an included library, but was imagining possibly a better method might be as follows:
Where tr = document.getElementById("table1").rows,
an element is accessed as tr[index].cells[0].textContent
So this tr looks as if it is an array of rows.
However
tr = document.getElementById("table1").rows;
tr.sort(function(a, b) {
return b.cells[0].textContent - a.cells[0].textContent; //order high to low
})
fails, because it says tr.sort is not a function. And table.rows does seem defined as an Object instead of an Array. Don't know how that differs, but rows looks and acts like an array.
Is there some workaround to allow this array method to work with Javascript sort?
Response to question in the comment:
Table is complicated because each row item is actually two adjacent rows. Plus a few TD are blank, causing numeric NaN errors unless handled. I only sort first row of 2, but move two rows. But I do have additional simple ordinary tables that could be sorted. 17 columns, one row looks like
<tr><td><a href="https://www.morningstar.com/funds/xnas/vfiax/performance">VFIAX</a>
><td>5.47<td>-36.97<td>26.62<td>15.05<td>2.08<td>15.96<td>32.33<td>13.64<td>1.36<td>11.93<td>21.79<td>-4.43<td>31.46<td>18.37
><td>13.34<td><b>S&P 500 Index</b><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
and my current code is
function sortTable(tr, sort_col) {
var len, i, x, y, a, b;
len = tr.length - 2;
i = 1;
while (i < len) {
for (i = 1; i < len; i += 2) { //double rows for each item
a = tr[i].cells[sort_col].textContent;
b = tr[i + 2].cells[sort_col].textContent; //text for ticker in col 0
if (sort_col > 0) {
a = parseFloat(a); //parseFloat because it is reading string fields like 12.6%
b = parseFloat(b);
if (isNaN(a)) a = 0; //early blank values cause NaN errors
if (isNaN(b)) b = 0;
}
if ( (sort_col == 0)? a > b : a < b) {
tr[i].parentNode.insertBefore(tr[i + 2], tr[i]);
tr[i+1].parentNode.insertBefore(tr[i + 3], tr[i + 1]); //2nd of double rows
break;
}
} // i
}
Sorted = 1;
}