1

I am trying to apply the sorting method to one of the columns in my table. That column is having numerical values and empty values ("--"). I would like to sort the values in ascending and descending manner. And I want all the empty values should go to the bottom of the table in both sorting types.

Could anyone please suggest a custom sorting function to use with react-table-6?

Thank You...

TheRakeshPurohit
  • 551
  • 1
  • 6
  • 22

1 Answers1

1

It's crazy that you asked this because I just finished working on this exact problem with the exact same requirements -- lucky you!

This is in TypeScript, but you can remove the types if you want.

The columns:

  const columns: Column[] = useMemo(
    () => [
      {
        Header: 'Rank',
        accessor: 'rank',
        sortType: rankSort, // This is the rankSort() function below
        maxWidth: 10,
      },
      ...
    ],
    []
  );

This is the ranking function:

const getRankValueString = (value: number, desc?: boolean): string => {
  let stringValue = value.toString();

  if (stringValue === '--') {
    if (desc) {
      stringValue = '-9999999';
    } else {
      stringValue = '9999999';
    }

    return stringValue;
  }

  for (let i = stringValue.length; i < 6; i++) {
    stringValue = `0${stringValue}`;
  }

  return stringValue;
};

const rankSort = (
  rowA: Row,
  rowB: Row,
  columnId: string,
  desc?: boolean
): number => {
  return getRankValueString(rowA.values[columnId], desc).localeCompare(
    getRankValueString(rowB.values[columnId], desc)
  );
};

It's a bit hacky, but it sorts values up to 6 digits. I'm open to optimizations.

tsteve
  • 549
  • 1
  • 7
  • 16