# Simple table sorting using plain Javascript

This is a simple and clean script for sorting a specific column in a table. You could edit and parametrize it to add more customization, but I wanted to share the base concept.

Base concept (I think its a pretty cool 3 line code):

t = document.getElementById('myTable');
[...t.tBodies[0].rows] //Transforming HTMLCollection to an Array
.sort( (a,b) => a.cells[0].textContent < b.cells[0].textContent)
.forEach(r => t.tBodies[0].appendChild(r)) //Appending the rows themselves, so the table is reordered without needing to create any new element


Parametrization example:

function sortTableColumn(tableID, columnIndex){
t = document.getElementById(#\${tableID});
[...t.tBodies[0].rows]
.sort( (a,b) => a.cells[columnIndex].textContent < b.cells[columnIndex].textContent)
.forEach(r => t.tBodies[columnIndex].appendChild(r))
}


Concerns:

• Performance: is the use of spread operator ok here? Or is Array.from preferred?

• Visual sorting: Since you're re-appending each element one by one, in a large table the user would see the table arranging until it is done. I couldn't think of a way of "one shotting" the appending without affecting performance too much. Maybe adding a loading overlay is the best solution?

• What if we're dealing with a table with 1000+ records? What could go wrong?

Table (any table with one body should work):

     <table id="myTable">
<tr>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
<tbody>
<tr>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>Larry</td>
<td>the Bird</td>