I am having a data like below in the p-table column
SUN - 1, SUN - 2, ... SUN - 11, SUN - 12,
While doing sort it is behaving abnormal. It is not sorting based on number after dash. How to achieve sorting with this format.
I tried to add custom sort
.html
<p-table sortFunction)="customSort($event)" [customSort]="true"></p-table>
.ts
customSort(event: SortEvent) {
event.data.sort((data1, data2) => {
let value1 = data1[event.field];
let value2 = data2[event.field];
let result = null;
if (value1 == null && value2 != null)
result = -1;
else if (value1 != null && value2 == null)
result = 1;
else if (value1 == null && value2 == null)
result = 0;
else if (typeof value1 === 'string' && typeof value2 === 'string')
result = value1.localeCompare(value2);
else
result = (value1 < value2) ? -1 : (value1 > value2) ? 1 : 0;
return (event.order * result);
});
}
Here I link stacblitz code for similar issue: https://stackblitz.com/edit/primeng-tablesort-demo-rfn6zn?file=src%2Fapp%2Fproductservice.ts,src%2Fassets%2Fproducts-small.json
You can extract the number value, then do the compare when the values contain SUN
. Please check the below code.
sortTableData(event) {
console.log(event);
event.data.sort((data1, data2) => {
let value1 = data1[event.field];
let value2 = data2[event.field];
let result = null;
if (value1 == null && value2 != null) {
result = -1;
} else if (value1 != null && value2 == null) {
result = 1;
} else if (value1 == null && value2 == null) {
result = 0;
} else if (typeof value1 === 'string' && typeof value2 === 'string') {
if (value1.includes('SUN') && value2.includes('SUN')) {
const leftSplit = value1.split(' - ');
const rightSplit = value2.split(' - ');
const left = leftSplit.length ? +leftSplit[1] : 0,
right = rightSplit.length ? +rightSplit[1] : 0;
result = left < right ? -1 : left > right ? 1 : 0;
} else {
result = value1.localeCompare(value2);
}
} else {
result = value1.localeCompare(value2);
}
return event.order * result;
});
}