T
TanStack16mo ago
inland-turquoise

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
tak40548798
StackBlitz
table-shadcn - StackBlitz
Next generation frontend tooling. It's fast!
7 Replies
other-emerald
other-emerald16mo ago
Sorting Guide | TanStack Table Docs
Examples Want to skip to the implementation? Check out these examples:
other-emerald
other-emerald16mo ago
other-emerald
other-emerald16mo ago
define which sortingFn you want to use, and use sortUndefined: 'last'
inland-turquoise
inland-turquoiseOP16mo 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
other-emerald16mo ago
In your accessorFn, just fallback to undefined instead of empty string
inland-turquoise
inland-turquoiseOP16mo 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
other-emerald16mo ago
Of course upgrade We always recommend updating to the latest version available

Did you find this page helpful?