2
\$\begingroup\$

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?

Fiddle: http://jsfiddle.net/ppgab/nu0q62br/22/

Table (any table with one body should work):

     <table id="myTable">
        <thead>
            <tr>
                <th scope="col">First</th>
                <th scope="col">Last</th>
                <th scope="col">Handle</th>
            </tr>
        </thead>
        <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>
                <td>@twitter</td>
            </tr>
        </tbody>
    </table>
\$\endgroup\$
  • \$\begingroup\$ Can you add the html table example too :) \$\endgroup\$ – G.aziz Jan 30 at 16:02
  • 1
    \$\begingroup\$ @G.aziz sure, added the fiddle too \$\endgroup\$ – Mojimi Jan 30 at 16:05
  • \$\begingroup\$ "user would see the table arranging" ... not at all likely to be visible. For larger set will get better performance sorting outside the dom and replacing tbody all at one time \$\endgroup\$ – charlietfl Feb 3 at 17:30
  • \$\begingroup\$ @charlietfl yes but, is replacing the whole tbody at once better performance? \$\endgroup\$ – Mojimi Feb 5 at 11:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.