My table has two columns: insdate
and resdate
, both containing date data. I am looking to sort the table based on these columns. For instance, when a user clicks the resdate
column, I want to be able to sort it in either increasing or decreasing order.
I attempted something similar to what is shown in this tutorial.
The data is retrieved as JSON from a webservice, with dates being returned as strings. Here's an example of the data returned:
logs = [
{ insdate: '11.12.2018 06:41:25', resdate: '11.12.2018 06:41:26' },
{ insdate: '10.12.2018 06:42:24 ', resdate: '10.12.2018 06:42:24' },
{ insdate: '10.12.2018 06:42:29', resdate: '10.12.2018 06:42:29'},
{ insdate: '12.12.2018 06:45:00', resdate: '12.12.2018 06:45:00' },
{ insdate: '11.12.2018 06:45:47', resdate: '11.12.2018 06:45:47' },
{ insdate: '10.12.2018 06:46:42', resdate: '10.12.2018 06:46:42' },
{ insdate: '10.12.2018 06:46:42', resdate: '' },
{ insdate: '', resdate: '12.12.2018 07:16:50' },
];
The date format is dd.MM.yyyy HH:mm:ss
, and results are ordered by insdate
on the server side. It is important to note that insdate
and resdate
may have empty values.
In my application, I have defined:
<th (click)="sortType('resdate')" [class.active]="sortBy==='resdate' ">ResDate</th>
in my app.component.html file.
In the app.component.ts file, I have implemented the following function:
sortType(sort: string)
{
this.copyLogs=this.logs;
if(sort==='resdate'){
this.logs=this.copyLogs.sort(this.sortByResDate);
}
}
sortByResDate(r1: any, r2:any){
let d1=moment(r1.resdate, 'dd.MM.yyyy HH:mm:ss').unix();
let d2 = moment(r2.resdate, 'dd.MM.yyyy HH:mm:ss').unix();
if(d1>d2) {
return 1;
}
else if(d1===d2) {
return 0;
}
else return -1;
}
Even though I used Unix time for comparison due to the dates being strings, the sorting did not turn out as expected. While the functions are being accessed and sorting is working, it is not correct :).
If anyone can point out where I might be going wrong, I would greatly appreciate it!