Search⌘ K

Adding Descending Functionality to Sort

Explore how to modify a generic TypeScript sort function to support ascending and descending order. Learn to add a SortDirection component in React with state management and user input via radio buttons. Understand design choices for implementing sort direction and their impact on UI and code structure.

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.

TypeScript 3.3.4
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() ...