Note: This is a follow up to the Data Table question, you should complete that question first before attempting this question.
In Data Table, we built a users data table that displays users in a paginated format. Data tables often allow sorting rows by specific columns in both ascending and descending order.
The skeleton code uses the solution of Data Table, but you are free to use your own solution as a starting point.
We'll build on top of Data Table's solution.
A common follow up question to a paginated data table is to add sorting features, sort the data by the available columns.
The new data needed for a data table that allows for sorting is the column to be sorted by and the direction to sort. There are two approaches to represent this configuration:
name-asc, name-desc, etc.).name, age, etc.) and sort direction (asc and desc).Both approaches are viable but it is probably clearer to have two separate fields.
These state values are set/toggled by clicking on the table headers.
We implement a function sortUsers that takes in the the list of users, the current sort field, and sort direction. It will return the list of users sorted by the specified field in that order.
A basic way to do the sorting is to use a switch-case statement for each possible field and implement the sorting logic within the case. Recall that there are two values types within the table – strings for name and occupation, and numbers of id and age. Sorting strings has to be done via String.prototype.toLocaleCompare() and should not be done using the > and < operators.