Open
Description
material-react-table version
2.13.1
react & react-dom versions
18.2.0
Describe the bug and the steps to reproduce it
Custom sortingFn not applying with sortUndefined: 'last' config
Issue Description
I'm having an issue with a custom sorting function in TanStack Table (Material React Table). I've created a custom sort function to treat zero values as undefined and sort them last, but it's not working as expected when combined with sortUndefined: 'last'
.
Reproduction Steps
- Created a custom sort function called
mapZeroToUndefinedSort
- Registered it in table config under
sortingFns
- Applied it to a column with
sortUndefined: 'last'
- Zero values are not being sorted to the end as expected
Expected Behavior
- When column is sorted, values of 0 should be treated as undefined
- These undefined (0) values should be sorted to the end with
sortUndefined: 'last'
Actual Behavior
- Zero values appear mixed in with other values
- The
sortUndefined: 'last'
setting doesn't seem to apply to zero values mapped to undefined
Question
Is there something wrong with my approach? Should I be handling the undefined sorting completely within my custom sort function instead of relying on sortUndefined: 'last'
? Any guidance would be appreciated!
Minimal, Reproducible Example - (Optional, but Recommended)
My Implementation
Custom Sort Function:
// common/utils/customTableSort.utils.ts
import { SortingFn } from '@tanstack/react-table';
export const mapZeroToUndefinedSort: SortingFn<unknown> = (rowA, rowB, columnId) => {
const a = rowA.getValue<number | null | undefined>(columnId);
const b = rowB.getValue<number | null | undefined>(columnId);
// Map 0 to undefined so sortUndefined:'last' can handle it
const effectiveA = a === 0 ? undefined : a;
const effectiveB = b === 0 ? undefined : b;
// If both are non-undefined (and non-zero), perform standard numeric comparison
// Also handle potential nulls as smallest
if (effectiveA !== undefined && effectiveB !== undefined) {
const valA = effectiveA ?? -Infinity;
const valB = effectiveB ?? -Infinity;
return valA - valB;
}
// If one or both are undefined (originally 0 or actually undefined/null),
// return 0. The sortUndefined logic should handle them.
return 0;
};
Column Definition:
{
accessorKey: `data.${selectedYear}.eac`,
header: 'EAC',
sortingFn: 'mapZeroToUndefinedSort',
sortUndefined: 'last',
// other properties...
}
Table Configuration:
const [table, { /* ... */ }] = useTableWithDefaultSettings({
// other config...
sortingFns: {
mapZeroToUndefinedSort,
},
// more config...
});
Screenshots or Videos (Optional)
No response
Do you intend to try to help solve this bug with your own PR?
None
Terms
- I understand that if my bug cannot be reliably reproduced in a debuggable environment, it will probably not be fixed and this issue may even be closed.
Metadata
Metadata
Assignees
Labels
No labels