Can someone help me with my customSort function for primeng table column sorting ? I have a Date column in my table which gets data from array of strings which i formated to 'hh:mm a' and its not sorting as i want it to sort (instead of sorting like 1am, 2am, 3am etc its currently sorting like 1am,1pm,10am,10pm, ... etc) i came up with this customSort function but its still giving me same result and everything else in my table sorts just fine with this customSort except the date column. Any help please?
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') {
const time1 = Date.parse('1970-01-01 ' value1);
const time2 = Date.parse('1970-01-01 ' value2);
console.log(value1);
if (time1 < time2) {
result = -1;
} else if (time1 > time2) {
result = 1;
} else {
result = 0;
}
} else {
result = value1 < value2 ? -1 : value1 > value2 ? 1 : 0;
}
return event.order * result;
});
}
in html table i added this attribute
code...
...
[customSort]="true"
(sortFunction)="customSort($event)"
...code
i have done some changes but still same sorting result
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 {
const time1 = new Date(`1970-01-01 ${value1.padStart(5, '0')}`);
const time2 = new Date(`1970-01-01 ${value2.padStart(5, '0')}`);
const timestamp1 = time1.getTime();
const timestamp2 = time2.getTime();
if (timestamp1 < timestamp2) {
result = -1;
} else if (timestamp1 > timestamp2) {
result = 1;
} else {
result = 0;
}
}
return event.order * result;
});
}
CodePudding user response:
why not add a new property "minutes" like
data.forEach(x=>{
const values=x.date?x.date.split(' '):null;
const hourMinutes=values?values[0].split(":"):null;
x.minutes=hourMinutes?( hourMinutes[0])*60 ( hourMinutes[1]):-999
if (values && values[1]=="pm")
x.minutes =12*60
})
Then, the only is sorted by minutes
<ng-container matColumnDef="date" >
<th mat-header-cell *matHeaderCellDef mat-sort-header="minutes">
Date
</th>
<td mat-cell *matCellDef="let element"> {{element.date}} </td>
</ng-container>