1

I have created a lightning datatable in which I have column with number datatype. However when I click on it, it is getting sorted based on text and not on number.

Here is how it shows in Console

enter image description here

Here is my code:

<lightning-datatable key-field="id" 
                     data={dataFromServer} 
                     columns={headerColumns} 
                     hide-checkbox-column = "true"
                     enable-infinite-loading= "false" 
                     onrowaction={handleRowActions}
                     default-sort-direction={defaultSortDirection}
                     sorted-direction={sortDirection}
                     sorted-by={sortedBy}
                     is-loading = {loadingFinished}
                     onsort={onHandleSort}>
</lightning-datatable>
onHandleSort(event) {
    const { fieldName: sortedBy, sortDirection } = event.detail;
    console.log('MVK-->'+JSON.stringify(event.detail));
    const cloneData = [...this.dataFromServer];
    cloneData.sort(this.sortBy(sortedBy, sortDirection === 'asc' ? 1 : -1));
    this.dataFromServer = cloneData;
    this.sortDirection = sortDirection;
    this.sortedBy = sortedBy;
}

sortBy(field, reverse, primer) {
    const key = primer ? function(x) {
                             return primer(x[field]);
                         } : function(x) {
                             return x[field];
                         };

    return function(a, b) {
        a = key(a);
        b = key(b);
        return reverse * ((a > b) - (b > a));
    };
}

1 Answer 1

1

If your data is sorting by text, then that means the data that came from the server was text. You'll want to convert it to numeric data before sorting, or use a primer function.

const numberPrimer = (value) => ((''+value).match(/^\d+(\.\d+)*$/)? parseFloat(value):value);
cloneData.sort(this.sortBy(sortedBy, sortDirection === 'asc' ? 1 : -1, numberPrimer));

You might need a conditional here, if you have potentially numeric and text strings mixed in the same column. Hopefully, however, this will get you started.

3
  • thanks fox! this seems correct, actually, while saving this, I'm getting 'Invalid regular expression flag error' is this because of value parameter?
    – mvk1991
    Aug 2, 2021 at 5:07
  • @mvk1991 No, there was a typo in my example, /^\d+(\.\d+)*/$ should have been /^\d+(\.\d+)*$/.
    – sfdcfox
    Aug 2, 2021 at 5:10
  • thanks fox!! worked like a charm :) as always thanks much!!
    – mvk1991
    Aug 2, 2021 at 5:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .