FlashcardNot attempted
Sortable table: comparator and markup
Recall it before you reveal
What makes a sortable data table correct, both the sort itself and the header markup?
Space to reveal
Show answer & explanation
- Sort, then paginate: sort the whole dataset (or send the sort to the server and restart at page 1), never just the loaded rows.
- Compare by type: numbers with
a - b, dates by timestamp, strings withIntl.Collator(case- and accent-aware); empty values last in both directions. - Stable:
Array.prototype.sortis stable since ES2019; for desc flip the sign rather than reversing, and copy first ([...rows]ortoSorted). - Toggle: same column flips asc/desc, a new column starts asc.
- Markup:
<th scope="col">containing a<button type="button">;aria-sorton the sorted header only; arrow glypharia-hidden; a<caption>naming the table and current sort.