[英]Sorting Data in Angular in Ascending/Descending on click of a button
[英]How reuse logic for sorting in ascending and descending in angular typescript
我正在開發 angular 應用程序,我可以在其中按升序和降序對數據進行排序。雖然一切正常,但我想優化我的代碼,這樣我就不會重復自己並編寫高效的代碼。
這是控制台中控制台示例數據中的示例數據
我有一個對象數組,我想按 onclick 的升序和降序對數據進行排序。每次我為每個字段調用一個函數時,是否有更好的方法來做到這一點
這是我的代碼
數據.ts
sortedData
]
private isAscendingSort: boolean = false;
sortByMaxCases(sortedDataBasedOnDate) {
this.isAscendingSort = !this.isAscendingSort;
console.log(this.isAscendingSort)
sortedDataBasedOnDate.forEach(item => item.statewise.sort(function (a, b) {
if (b.confirmed < a.confirmed) {
return -1;
}
if (b.confirmed > a.confirmed) {
return 1;
}
return 0;
}))
if (!this.isAscendingSort) {
console.log(this.isAscendingSort)
sortedDataBasedOnDate.forEach(item => item.statewise.sort(function (a, b) {
if (a.confirmed < b.confirmed) {
return -1;
}
if (a.confirmed > b.confirmed) {
return 1;
}
return 0;
}))
}
}
// similary I have
sortAscendingActive(sortedData)(){..} // here with same logic compairig a.active > b.active
sortAscendingActive(sortedData){....} // compairig a.confirm > b.confirm
sortAscendingActive(sortedData){..} // compairig a.death> b.death
數據組件.html
<tr>
<th (click)="sortAscending(sortedData)"> State </th>
<th (click)="sortAscendingActive(sortedData)"> Active Cases </th>
<th (click)="sortAscendingConfirmed(sortedData)"> Confirmed Cases </th>
<th (click)="sortAscendingDeath(sortedData)"> Death </th>
</tr>
在這里,我在 SortedData 中獲取整個數據,然后我在單擊函數時執行排序,但這看起來很笨拙。有沒有更好的方法使我的代碼高效
也許你可以使用這樣的東西。 也傳遞您想要排序的文件。
我還沒有處理 isAscending 的值應該是什么。 我想你可以弄清楚。
sortDataByField(sortedDataBasedOnDate, fieldName, isAscending) {
sortedDataBasedOnDate.forEach(item => item.statewise.sort(function (a, b) {
return (a[fieldName] - b[fieldName]) * (isAscending ? 1 : -1);
}));
}
sortDataByField(sortedData, 'confirmed', true);
sortDataByField(sortedData, 'active', true);
sortDataByField(sortedData, 'death', true);
您可以將變量作為字符串傳遞並使用方括號訪問它們
<tr>
<th (click)="sort('state')"> State </th>
<th (click)="sort('active')"> Active Cases </th>
<th (click)="sort('confirmed')"> Confirmed Cases </th>
<th (click)="sort('deaths')"> Death </th>
</tr>
export class AppComponent {
stateAsc: boolean = false;
activeAsc: boolean = false;
confirmedAsc: boolean = false;
deathAsc: boolean = false;
sort = variable => {
// we can access the value like this using square bracket
console.log(this[`${variable}Asc`])
// or you can remove Asc from suffix and access like `this[variable]`
this.data[0] = {
...this.data[0],
statewise: variable === 'state' // Alphabets needed to sort differently
? this.data[0].statewise.sort((a, b) =>
this.stateAsc
? (a.state > b.state ? -1 : 1)
: (b.state > a.state ? -1 : 1)
)
: this.data[0].statewise.sort((a, b) =>
this[`${variable}Asc`]
? a[variable] - b[variable]
: b[variable] - a[variable]
)
}
// Change the boolean value
this[`${variable}Asc`] = !this[`${variable}Asc`]
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.