JavaScript Table Sorting (Part 2 of 2) — Enhancement!

Jason Knight
Level Up Coding
Published in
7 min readDec 11, 2020

--

If you’ve not already read it, be sure to check out part 1.

Photo by GEORGE DESIPRIS on Unsplash

In part 1 I showed how to take someone else’s simple example, and give it a bit of spit and polish cutting the code size almost in half. Since it was already tiny, that now gives us room to enhance it with more functionality.

In particular the use of two objects containing our sort types and data gathering methods lays the groundwork for easily adding more types of sorts.

New CAPTION and THEAD Markup

To show off our new filters we need a new table with new data.

The table caption/header is where most of the changes take place:

<table>
<caption data-tablesort-reset>Regex, DateTime, Input sorting</caption>
<thead>
<tr>
<th
scope="col"
data-tablesort="text"
>Name</th>
<th
scope="col"
data-tablesort="number"
data-tablesort-rxmatch="^\s*([0-9]+)"
>Place</th>
<th
scope="col"
data-tablesort="date"
>When</th>
<th
scope="col"
data-tablesort="valueText"
>Designation</th>
</tr>
</thead>

The data- attributes are for the following:

data-tablesort-reset

--

--

Accessibility and Efficiency Consultant, Web Developer, Musician, and just general pain in the arse