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
shalini sharma 24shalini sharma 24 

sorting in lightning dataTable

Hi ,

I am doing sorting at the client side in helper class in lightning datatable using the below code. However, I am receiving null values in few columns and that is impacting the sorting of my data. How can I handle the null values to show at the last in the sorted table?

 sortData: function (cmp, fieldName, sortDirection) {
        var data = cmp.get("v.mydata");
        var reverse = sortDirection !== 'asc';
        data.sort(this.sortBy(fieldName, reverse))
        cmp.set("v.mydata", data);
    },
    sortBy: function (field, reverse, primer) {
        var key = primer ?
            function(x) {return primer(x[field])} :
            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));
        }
    },
 
Best Answer chosen by shalini sharma 24
Ashif KhanAshif Khan
Hi  shalini,

You have to make some changes in sortBy action as given below
sortBy: function (field, reverse, primer) {
        var key = primer ?
            function(x) {return primer(x[field])} :
            function(x) {return x[field]};
        reverse = !reverse ? 1 : -1;
        return function (a, b) {
            return a = key(a)?key(a):'', b = key(b)?key(b):'', reverse * ((a > b) - (b > a));
        }
    },

Regards
Ashif
 

All Answers

Ashif KhanAshif Khan
Hi  shalini,

You have to make some changes in sortBy action as given below
sortBy: function (field, reverse, primer) {
        var key = primer ?
            function(x) {return primer(x[field])} :
            function(x) {return x[field]};
        reverse = !reverse ? 1 : -1;
        return function (a, b) {
            return a = key(a)?key(a):'', b = key(b)?key(b):'', reverse * ((a > b) - (b > a));
        }
    },

Regards
Ashif
 
This was selected as the best answer
MagulanDuraipandianMagulanDuraipandian
Check the below link
http://www.infallibletechie.com/2018/03/lighting-data-table-sorting-example.html
It should work. Check the attributes used and check whether they are initialized.
Wade JonesWade Jones
I have Same problem! Thanks Ashif for providing excellent solution..https://chasebanklogin.us
ravikanth samudrala 3ravikanth samudrala 3
@Thanks Ashif worked like Charm.
Alfonso de la Cuadra MartinezAlfonso de la Cuadra Martinez
Thanks @Magulan and @Ashif, it works perfectly.
harsha B R 9harsha B R 9
Logic is working for data which contains null values.Assume,if the data contains characters starting with number and some data starting with alphabets.Above code is not working in such kind of scenarios.

It would be great if you can share the code for the above mentioned scenarios.