JavaScript Mapping Library
Just a quick note. Last year, I blogged a demo of a web component that lets you wrap an existing HTML table and progressively add table sorting. I’m rather proud of that demo and was actually planning on doing a quick video about it, but while testing I encountered two small bugs that somehow missed my earlier rigorous testing. (And by rigorous testing I mean a few minutes of clicking around.)
Specifically, the issue is in the "when clicking to sort, notice if we sorted this column before and if so, reverse the sort" area:
sortCol(e,i) { let sortToggle = 1; if(this.lastSort === i) { this.sortAsc = !this.sortAsc; if(!this.sortDir) sortToggle = -1; } this.lastSort = i; this.data.sort((a,b) => { if(a[i] < b[i]) return -1 * sortToggle; if(a[i] > b[i]) return 1 * sortToggle; return 0; }); this.renderTable();}
In the function above, i simply refers to the index of the column that is being sorted. My thinking at the time was – the default is ascending, but if you are clicking the same column as last time, reverse it.
i
There are two bugs here:
sortDir
sortAsc
So the fix looks like this:
sortCol(e,i) { let sortToggle = 1; if(this.lastSort === i) { this.sortAsc = !this.sortAsc; if(!this.sortAsc) sortToggle = -1; } else this.sortAsc = true; this.lastSort = i; this.data.sort((a,b) => { if(a[i] < b[i]) return -1 * sortToggle; if(a[i] > b[i]) return 1 * sortToggle; return 0; }); this.renderTable();}
I’m going to edit the older blog post now and correct the samples, but if you just want to see the finished version, here it is:
See the Pen PE Table for Sorting (2) – Edited by Raymond Camden (@cfjedimaster) on CodePen.
Raymond Camden
You must be logged in to post a comment.
This site uses Akismet to reduce spam. Learn how your comment data is processed.