I have set of Data having date along with the list. I need to sort the fields. I am able to sort all other fields except Date. Find below the code. And also if I sort the column “Name”, the other two column’s icon also changing. I want the solution like if i sort the particular column, that particular column arrow icon should change not other two columns icon.
So My Question is how to sort the date Column and and the icon of that particular column should only change when i tap on that particular column.
HTML
<ion-row class="header-row"> <ion-col size="1" tappable (click)="sortBy('Name')"> <b>FirstName</b> <ion-icon name="arrow-down" *ngIf="sortDirection==1"></ion-icon> <ion-icon name="arrow-up" *ngIf="sortDirection==2"></ion-icon> </ion-col> <ion-col size="1" tappable (click)="SortBy('PurchaseDate')"> <b>Purchase Date</b> <ion-icon name="arrow-down" *ngIf="sortDirection==1"></ion-icon> <ion-icon name="arrow-up" *ngIf="sortDirection==2"></ion-icon> </ion-col> <ion-col size="1" tappable (click)="sortBy('CarName')"> <b>Car Name</b> <ion-icon name="arrow-down" *ngIf="sortDirection==1"></ion-icon> <ion-icon name="arrow-up" *ngIf="sortDirection==2"></ion-icon> </ion-col> </ion-row> <ion-card class="cardbottomfield colpadding"> <div *ngFor="let purchase of purchasedetails ; trackBy: trackByFn" class="data-row"> <ion-row> <ion-col size="1"> {{purchase.Name}} </ion-col> <ion-col size="1" > {{purchase.PurchaseDate}} </ion-col> <ion-col size="1"> {{purchase.CarName}} </ion-col> </ion-row> </div> </ion-card>
TYPESCRIPT
sortBy(key) { this.sortKey= key; this.sortDirection++; this.sort(); } sort() { if(this.sortDirection == 1) { this.purchasedetails = this.purchasedetails.sort((a,b) => { const valA = a[this.sortKey]; const valB = b[this.sortKey]; return valA.localeCompare(valB); }); } else if (this.sortDirection == 2) { this.purchasedetails = this.purchasedetails.sort((a,b) => { const valA = a[this.sortKey]; const valB = b[this.sortKey]; return valB.localeCompare(valA); }); } else { this.sortDirection = 0; this.sortKey = null; } }
Advertisement
Answer
- Create
Date
objects from date strings - Sort ascending based on
valueOf
const parseDate = (dateStr) => { const [d, m, y] = dateStr.split('.') .map(Number) return new Date(y, m - 1 /* month is 0-indexed */, d) } const sortDatesAsc = (dateStr1, dateStr2) => { return parseDate(dateStr2).valueOf - parseDate(dateStr1).valueOf } console.log([ '10.01.2010', '01.10.2010', '10.10.2020', ].sort(sortDatesAsc))