I am using primeNg <p-table> to implement custom sort for "Quarterly Results" field.
The date in the "Quarterly Results" field is as below:
Q3-2017
2018
2017
Q1-2016
2000
Q3-2018
Q2-2012
Source : https://primefaces.org/primeng/#/table/sort
To sort the data I have done below code:
HTML:
<p-table [value]="documents" (sortFunction)="customSort($event)" [customSort]="true">
<ng-template pTemplate="header">
<tr>
<th [pSortableColumn]="quarter">
Quarterly Results
<p-sortIcon [field]="quarter"></p-sortIcon>
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-doc>
<tr>
<td>
{{doc.quarter}}
</td>
</tr>
</ng-template>
</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);
});
}
The problem I am facing is when I sort, the data is not coming is proper sorted order. In first sort click the data comes like (Q1-2016 is coming before Q2-2012):
2000
2017
2018
Q1-2016
Q2-2012
Q3-2017
Q3-2018
and in second sort click data come as below (Q2-2012 is coming before Q1-2016):
Q3-2018
Q3-2017
Q2-2012
Q1-2016
2018
2017
2000
I want the data to be sorted like
2000
2017
2018
Q2-2012
Q1-2016
Q3-2017
Q3-2018
and on second sort click like:
Q3-2018
Q3-2017
Q1-2016
Q2-2012
2018
2017
2000
Please guide me where did I go wrong that my data is not coming in proper sorted order, I also tried 'return value1 > value2 ? 1 : (value1 < value2 ? -1 : 0)'. Which logic am I missing on? Please suggest
I think the problem is in this line result = (value1 < value2) ? -1 : (value1 > value2) ? 1 : 0;
PS: I cannot use