May 2017
Intermediate to advanced
448 pages
10h 10m
English
Our final sorting enhancement is to allow for both ascending and descending sort orders. When the user clicks on a column that is already sorted, we want to reverse the current sort order.
To reverse a sort, all we have to do is to invert the values returned by our comparator. We can do this with a simple direction argument to the sort comparator:
const comparator = (a, b, direction = 1) => a < b ? -direction : (a > b ? direction : 0);
If direction equals 1, then the sort will be the same as before. If it equals -1, the sort will be reversed. By combining this concept with some classes to keep track of the current sort order of a column, achieving alternating sort directions is simple:
// ....on('click', (e) ...Read now
Unlock full access