I'm trying to make a sortable table that fills with sortable information. Some of the information could come back as ? or -- in either case, I'd like that value to be "ignored" and pushed to the end no matter the sort direction. I am using Tanstack and tried this simple sort function:
const customSortingFunction = (rowA, rowB, columnId) => {
const specialValues = ['?', '--']
const valueA = rowA.getValue(columnId)
const valueB = rowB.getValue(columnId)
const isSpecialA = specialValues.includes(valueA)
const isSpecialB = specialValues.includes(valueB)
if (isSpecialA && isSpecialB) {
return 0
} else if (isSpecialA) {
return 1
} else if (isSpecialB) {
return -1
}
return valueA.localeCompare(valueB, 'en', {numberic: true})
}
here's that column object as it exists in the list of columns:
{
accessorKey: 'location',
header: 'Location',
cell: props => <p>{props.getValue()}</p>,
sortingFn: 'customSortingFunction'
},
Here's my Tanstack initialization:
const table = useReactTable({
data: buildTableData(data),
columns: getColumn(vl),
sortingFns: {
customSortingFunction
},
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
state: {
sorting: sorting
},
enableSortingRemoval: false,
onSortingChange: setSorting
})
I know the function is being called when I sort by location through console.counts and logs, it sorts perfectly but also perfectly fails to ignore the ? and or -- values. I have tried changing the numbers that returns and many other functions. It just keeps sending ? to the top on desc no matter what I do. Any ideas? Thanks!
It may be a small typo in your localeCompare options. The correct option may be 'numeric' (not 'numberic'). Also, for better handling of special values, you may want to modify your custom sort function. Here is an updated version:
Make sure to update your sorting function in the column definition as well:
With these changes, your custom sorting function should work as intended, ignoring '?' and '--' values and pushing them to the end of the sorted list.