This is a quick post to understand how sorting is accomplished in lightning datatable (LWC).
Lightning datatable provides an onsort attribute which will allow us to implement the sorting for the elements in the table. You could implement sorting locally or via making a server call.
You would generally implement this type of sorting if you know that the list of elements is going to be small and limited. For example, if you’re displaying a list of approval history records for a particular record, you know that the number of records won’t be more (assuming you have a simple approval process).
In the example below, we have created a simple component which displays the list of the contacts (firstName and lastName). When the header column is clicked the onsort handler is invoked, the field and the sort order is passed and using this information the list is sorted.
Sorting via server call
As you would have guessed this would be useful when you have a huge list and you are displaying a small chunk of the total records.
The major advantage of this method is that you need not implement any custom logic at all. The sorting will be completely handled by the SOQL. Another thing to note here is that you will have to disable the data-table so that the user’s do not click on the header in the time the server call is being executed.