...
/Adding Descending Functionality to Sort
Adding Descending Functionality to Sort
Add the ability to sort in ascending or descending order with the generic sort function and a React component.
Although we have built out our full UI for searching and sorting, there’s no way to specify if we want our sorters to show data in ascending or descending order.
To fix this, let’s return to our genericSort()
function. We can add an additional parameter to this function, called isDescending
.
export default function genericSort<T>(a: T, b: T, property: keyof T, isDescending: boolean) {if (a[property] > b[property]) {return 1;}if (a[property] < b[property]) {return -1;}return 0;}
Refactoring genericSort()
to handle the sorting direction
To reverse the sorting order, we could check the isDescending
flag at each point of return in our genericSort()
function, flipping the 1
and -1
signs. But, instead of doing this at each of the return statements, we can be a bit creative, write less code, and make it easier to understand. First, we’ll wrap what we currently have in genericSort()
...