javascriptreactjsmaterial-tablecolumnsortingcustom-sort

Getting the sorting order (asc/desc) from inside a material-table customSort function


Im new to react js and im trying to sort the dates...the problem is the dates have null value and i want the null dates to always appear at the last irrespective of the order('asc' or 'desc')....i have seen so many examples in stack overflow where they are using customsort by checking with the order...whether its asc or desc....im using materialtable and im unable to get hold of the sortingorder....how can i gethold of the sortingorder so i can implement the customsorting where the null dates always appear at the last....irrespective of asc or desc

i have tried customSort:(a,b)=> { return (b.paymentDate != null) - (a.paymentDate != null) || a.paymentDate - b.paymentDate ; }

this type....on my columns....but its working only for one way.....i want to gethold of the order...so i can write it according to asc or desc


Solution

  • Based on your example, it looks like your customSort function is expected to behave like Array.sort()'s compare function.

    Additionally, it looks like the customSort function gets passed the string "desc" as a 4th arg if the order is descending:

    if (columnDef.customSort) {
      if (this.orderDirection === "desc") {
        result = list.sort((a, b) => columnDef.customSort(b, a, "row", "desc"));
      } else {
        result = list.sort((a, b) => columnDef.customSort(a, b, "row"));
    

    So you can add a 4th param to your customSort, and handle the sorting of null values differently based on it; taking into account that the caller swaps a and b if order == 'desc'. What about:

    customSort: (a, b, type, order) => {
      let desc = order == "desc";
      
      if (a.paymentDate !== null && b.paymentDate !== null)
        return a.paymentDate - b.paymentDate;
      else if (a.paymentDate !== null)
        return desc ? 1 : -1;
      else if (b.paymentDate !== null)
        return desc ? -1 : 1;
      else
        return 0;
    }