LWC Lightning Datatable – Number column not getting sorted

javascriptlightning-datatablelightning-web-components

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));
    };
}

Best Answer

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.