I have been trying to set a presort similarly to this: https://www.primefaces.org/primereact/showcase/#/datatable/sort
The problem I am facing is that I would like to sort on render by a column which has a sortFunction defined by me.
I have a working sortFunction, but if I give the DataTable a sortField, it does not use it. On render the nulls are in front, which is the default sort of sortable but clicking the header uses the proper sortFunction, which sorts alpahabetically and sends nulls to the end
Is it possible to solve this somehow or should I let the presorting go?
Edit: I presorted the data and gave it to the DataTable that way, so it works but it is far from elegant, also it does not show the column to have the sorted arrows on render, but it might be helpful for someone:
const dataTableSortFunction = (value: any[]) => (event: ColumnSortParams): any[] => {
return [...value].sort((data1, data2) => {
const value1 = data1[event.field];
const value2 = data2[event.field];
if (value1 == null && value2 == null) return 0;
if (value2 == null) return -1;
if (value1 == null) return 1;
if (typeof value1 === "string" && typeof value2 === "string")
return value1.localeCompare(value2) * event.order;
if (value1 < value2) return -1 * event.order;
if (value1 > value2) return 1 * event.order;
return 0;
});
};
const myProductSort = dataTableSortFunction(products);
const preSortedProducts = myProductSort({ field: "category", order: -1 });
...
<DataTable value={preSortedProducts} className="p-datatable-sm">
<Column field="code" header="Code" sortable></Column>
<Column field="name" header="Name" sortable></Column>
<Column
field="category"
header="Category"
sortable
sortFunction={myProductSort}
></Column>
<Column field="quantity" header="Quantity" sortable></Column>
<Column field="price" header="Price" sortable></Column>
</DataTable>