Hello Everyone, In this post, we will see a code example that shows you, how you can implement sorting on lightning datatable columns. This example is very easy to implement in lightning components. So without wasting time let's begin,

Column sorting in lightning:datatable

For this task, I have create an apex class and a lightning component. In apex class, code simply return list of account that used in component. The key point is placed in component that help me to sort the datatable column.

1. Navigate to Developer Console | File | New | Apex Class and create a new apex class named DatatableHandler and replace the following code.

DatatableHandler.apxc

 public class DatatableHandler {    
@AuraEnabled
public static List<Account> getAccounts(){
return [SELECT Id,Name,Industry,AccountNumber,CreatedDate FROM Account limit 10];
}
}

2. Navigate to Developer Console | File | New | Lightning Component and create a new lightning component named ColumnSorting and replace the following block of code in their related files.

ColumnSorting.cmp

 <aura:component controller="DatatableHandler" implements="force:appHostable,flexipage:availableForAllPageTypes,force:hasRecordId" access="global" >
<aura:attribute name="results" type="Account[]"/>
<aura:attribute name="mycolumns" type="List"/>
<aura:attribute name="sortedBy" type="String" default="Name"/>
<aura:attribute name="sortedDirection" type="string" default="asc" />
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<lightning:layout multipleRows="true" horizontalAlign="center">
<lightning:layoutItem padding="around-small" size="12">
<lightning:datatable keyField="id" data="{!v.results}"
columns="{!v.mycolumns}"
resizeColumnDisabled="true"
hideCheckboxColumn="true"
onsort="{!c.sortColumn}"
sortedBy="{!v.sortedBy}"
sortedDirection="{!v.sortedDirection}"
/>
</lightning:layoutItem>
</lightning:layout>
</aura:component>
ColumnSortingController.js
 ({
doInit : function(component, event, helper) {
component.set('v.mycolumns', [
{label: 'Name', fieldName: 'Name',type: 'text',sortable:true},
{label: 'Industry', fieldName: 'Industry',type: 'text',sortable:true},
{label: 'AccountNumber', fieldName: 'AccountNumber',type: 'text',sortable:true},
{label: 'Created Date', fieldName: 'CreatedDate',type: 'date',sortable:true,
typeAttributes:{day:'numeric',month:'short',year:'numeric',hour:'2-digit',minute:'2-digit',second:'2-digit',hour12:true}}
]);
var action=component.get("c.getAccounts");
action.setCallback(this,function(e){
if(e.getState()=='SUCCESS'){
var results=e.getReturnValue();
console.log(results);
if(results.length>0){
component.set('v.results', results);
}
}
});
$A.enqueueAction(action);
},

sortColumn : function (component, event, helper) {
var fieldName = event.getParam('fieldName');
var sortDirection = event.getParam('sortDirection');
component.set("v.sortedBy", fieldName);
component.set("v.sortedDirection", sortDirection);
helper.sortData(component, fieldName, sortDirection);
},
})
ColumnSortingHelper.js
 ({
sortData: function (component, fieldName, sortDirection) {
var fname = fieldName;
var data = component.get("v.results");
var reverse = sortDirection !== 'asc';
data.sort(this.sortByfield(fieldName, reverse))
component.set("v.results", data);
},

sortByfield: function (field, reverse) {
var key = function(x) {return x[field]};
reverse = !reverse ? 1 : -1;
return function (a, b) {
return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
}
},
})

3. Preview component to see the output.

Output:

 

Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.