function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
kallam salesforce1kallam salesforce1 

I am trying to sort by columns in lightning data table but at some It is not getting sorted. Can someone help me ?

>>> TableSorting.Html
<template>
    <lightning-card title="Data Sorting in Lightning Datatable in LWC" icon-name="standard:contact" >
        <br/>
        <div style="width: auto;">
            <template if:true={data}>
                <lightning-datatable data={data}
                                     columns={columns}
                                     key-field="id"
                                     sorted-by={sortBy}
                                     sorted-direction={sortDirection}
                                     onsort={doSorting}
                                     hide-checkbox-column="true"></lightning-datatable>
            </template>
        </div>
    </lightning-card>
</template>


>>>>>>>>> TableSorting.js

import { LightningElement,track,wire } from 'lwc';
import getContactsInfo from '@salesforce/apex/GetContacts.getContactsInfo';
const columns = [ { label: 'FirstName', fieldName: 'FirstName', sortable: "true"},
                  { label: 'LastName', fieldName: 'LastName', sortable: "true"},
                  { label: 'Phone', fieldName: 'Phone', type: 'phone', sortable: "true"},
                  { label: 'Email', fieldName: 'Email', type: 'email', sortable: "true" },];
export default class TableSorting extends LightningElement {
    @track data;
    @track columns = columns;
    @track sortBy;
    @track sortDirection;
 
    @wire(getContactsInfo)
    contacts(result) {
        if (result.data) {
            this.data = result.data;
            console.log(result.data)
            this.error = undefined;
        } else if (result.error) {
            this.error = result.error;
            this.data = undefined;
        }
    }
    doSorting(event) {
        this.sortBy = event.detail.fieldName;
        this.sortDirection = event.detail.sortDirection;
        this.sortData(this.sortBy, this.sortDirection);
    }
    sortData(fieldname, direction) {
        let parseData = JSON.parse(JSON.stringify(this.data));
        // Return the value stored in the field
        let keyValue = (a) => {
            return a[fieldname];
        };
        // cheking reverse direction
        let isReverse = direction === 'asc' ? 1: -1;
        // sorting data
        parseData.sort((x, y) => {
            x = keyValue(x) ? keyValue(x) : ''; // handling null values
            y = keyValue(y) ? keyValue(y) : '';
            // sorting values based on direction
            return isReverse * ((x > y) - (y > x));
        });
        this.data = parseData;
        console.log(this.data);
    }    
}

>>>>>>>>  Apex class
public with sharing class GetContacts {
   
    @AuraEnabled(Cacheable = true)
    public static list<Contact> getContactsInfo(){
       return  [SELECT Id,FirstName,LastName,Phone,Email from Contact];
    }
}

User-added imageIn Table you can find in 1st cloumn unable to sort particulsr NAme?
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Kallam,

Even I observed the same issue. I have used the apex class based sorting which is working as expected.

Html file will be same.

JS file.
 
import {LightningElement, wire, track} from 'lwc';
import getContacts from '@salesforce/apex/LWCDataTableSortingExample.getContacts';

// datatable columns with row actions. Set sortable = true
const columns = [ { label: 'FirstName', fieldName: 'FirstName', sortable: "true"},
                  { label: 'LastName', fieldName: 'LastName', sortable: "true"},
                  { label: 'Phone', fieldName: 'Phone', type: 'phone', sortable: "true"},
                  { label: 'Email', fieldName: 'Email', type: 'email', sortable: "true" },];

export default class DataTableSortingLWC extends LightningElement {
    @track data;
    @track columns = columns;
    @track sortBy='FirstName';
    @track sortDirection='asc';
 
    // retrieving the data using wire service
    @wire(getContacts,{field : '$sortBy',sortOrder : '$sortDirection'})
    contacts(result) {
        if (result.data) {
            this.data = result.data;
            this.error = undefined;
        } else if (result.error) {
            this.error = result.error;
            this.data = undefined;
        }
    }
    doSorting(event) {
        // calling sortdata function to sort the data based on direction and selected field
        this.sortBy = event.detail.fieldName;
        this.sortDirection = event.detail.sortDirection;
    }
}

Apex Class:
 
public with sharing class LWCDataTableSortingExample {
    @AuraEnabled(Cacheable=true)
    public static List <Contact> getContacts(String field, String sortOrder) {
        String query;
        query  = 'SELECT Id, FirstName, LastName, Phone, Email FROM Contact';
        if(field != null && sortOrder !=null){
            query += ' ORDER BY '+field+' '+sortOrder;
        }
        return Database.query(query);
    }
}

If this solution helps, Please mark it as best answer.

Thanks,
 
CharuDuttCharuDutt
Hii Kallam
Try Below Code
<template>
    <lightning-card title="Data Sorting in Lightning Datatable in LWC" icon-name="standard:contact" >
        

        <div style="width: auto;">
            <template if:true={data}>
                <lightning-datatable data={data}
                                     columns={columns}
                                     key-field="id"
                                     sorted-by={sortBy}
                                     sorted-direction={sortDirection}
                                     onsort={doSorting}
                                     hide-checkbox-column="true"></lightning-datatable>
            </template>
        </div>
    </lightning-card>
</template>
##################################

import { LightningElement,track,wire } from 'lwc';
import getContactsInfo from '@salesforce/apex/GetContacts.getContactsInfo';
const columns = [ 
{ label: 'FirstName', fieldName: 'FirstName', sortable: "true"}, 
{ label: 'LastName', fieldName: 'LastName', sortable: "true"}, 
{ label: 'Phone', fieldName: 'Phone', type: 'phone', sortable: "true"}, 
{ label: 'Email', fieldName: 'Email', type: 'email', sortable: "true" }];
export default class TableSorting extends LightningElement {
@track data; 
@track columns = columns; 
@track sortBy='FirstName'; 
@track sortDirection='asc'; 

   // retrieving the data using wire service
    @wire(getContactsInfo ,{field : '$sortBy',sortOrder : '$sortDirection'})
    contacts(result) {
        if (result.data) {
            this.data = result.data;
            this.error = undefined;
        } else if (result.error) {
            this.error = result.error;
            this.data = undefined;
        }
    }
    doSorting(event) {
        // calling sortdata function to sort the data based on direction and selected field
        this.sortBy = event.detail.fieldName;
        this.sortDirection = event.detail.sortDirection;
    }
}


public with sharing class GetContacts {
   
    @AuraEnabled(Cacheable = true)
    public static list<Contact> getContactsInfo(String field, String sortOrder) { 
String query; 
query = 'SELECT Id, FirstName, LastName, Phone, Email FROM Contact'; 
if(field != null && sortOrder !=null){ 
query += ' ORDER BY '+field+' '+sortOrder; 
} 
return Database.query(query);
}
}
Please Mark It As Best Answer If It Helps
Thank You!
Mohit Kumar 335Mohit Kumar 335
Hi Kallam,
Your code is working perfectly. The record mentioned in the highlighted row is in lowercase. The value of lowercase records are always greater than uppercase records. Thats why the highlighted record is comming in the last.