custom sortingFn problem
How can I implement custom sorting logic where:
Numbers are sorted numerically.
Empty strings are placed at the end.
For example:
// asc [6,'',2,'',4] => [2,4,6,'','']
// desc [6,'',2,'',4] => [6,4,2,'','']
// false [6,'',2,'',4] => [6,'',2,'',4]
const sortStatusFn: SortingFn<Order> = (rowA, rowB, _columnId) => {
// not working
const statusA = rowA.original.status;
const statusB = rowB.original.status;
if (statusA !== '' && statusB !== '') {
return statusA > statusB ? 1 : -1;
}
if (statusA === '') return 1;
if (statusB === '') return -1;
return 0;
};
However, within the function, I seem unable to determine whether the current sorting mode is 'asc', 'desc', or 'no sorting'.
Code:
https://stackblitz.com/edit/vitejs-vite-f47e9f?file=src%2FTestTable.tsx
7 Replies
other-emerald•16mo ago
have you read through the sorting guide? https://tanstack.com/table/latest/docs/guide/sorting#sorting-fns
Sorting Guide | TanStack Table Docs
Examples
Want to skip to the implementation? Check out these examples:
other-emerald•16mo ago
Sorting Guide | TanStack Table Docs
Examples
Want to skip to the implementation? Check out these examples:
other-emerald•16mo ago
define which sortingFn you want to use, and use
sortUndefined: 'last'
inland-turquoiseOP•16mo ago
I tried using sortUndefined, but in my case, there are no scenarios where a key does not exist.
ex:
{x:1,y:1},
{x:4},
{x:3,y:3},
{x:5,y:5},
{
accessorKey: 'y',
sortUndefined:'last'
}
result:
{x:1,y:1},
{x:3,y:3},
{x:5,y:5},
{x:4},
but my problem:
{x:1,y:1},
{x:4,y:""},
{x:3,y:3},
{x:5,y:5},
{
accessorKey: 'y',
sortUndefined: 'last'
}
result:
{x:4,y:""}, // not working
{x:1,y:1},
{x:3,y:3},
{x:5,y:5},
other-emerald•16mo ago
In your accessorFn, just fallback to undefined instead of empty string
inland-turquoiseOP•16mo ago
Thank you very much, this seems to work:
accessorFn: (row, _) => {
if (row.status === '') {
return undefined;
}
return row.status;
}
"sortUndefined " requires v8.16.0, but my project is using v8.10.3. Can I upgrade directly?
other-emerald•16mo ago
Of course upgrade
We always recommend updating to the latest version available