我有 2 個不同物件的陣列,我想在我的 Angular 應用程式中按日期排序。
物件 1:
約會ID:編號,約會日期:日期
物件 2:
cancelId:數字,cancelDate:日期
以下代碼按預約日期排序,如何同時按取消資料排序,以便我有一個組合排序串列?
let appointments = this.appointmentService.getAppointmentsForJob(this.jobId);
let cancellations = this.cancellationService.getCancellationsForJob(this.jobId);
forkJoin([appointments, cancellations]).subscribe(results => {
this.appointments = results[0];
this.cancellations = results[1];
this.loading = false;
this.combinedItems = ([]).concat(this.appointments, this.cancellations);
this.combinedItems = this.combinedItems.sort((a, b) => a.appointmentDate - b.appointmentDate);
console.log(this.combinedItems);
});
uj5u.com熱心網友回復:
您應該知道哪個屬性在排序中具有“更高”的優先級,我按照您給出的順序排列。首先是約會日期,然后是取消日期。
forkJoin([appointments, cancellations]).subscribe(results => {
[this.appointments, this.cancellations] = results;
this.loading = false;
this.combinedItems = [...this.appointments, ...this.cancellations];
const compareFn = (a: any, b: any) => {
const compareByAppDate = a.appointmentDate - b.appointmentDate;
const compareByCancelDate = a.cancelDate - b.cancelDate;
return compareByAppDate || compareByCancelDate;
}
this.combinedItems = this.combinedItems.sort(compareFn)
console.log(this.combinedItems);
});
uj5u.com熱心網友回復:
如果您想同時使用兩個日期,您可以像這樣更改排序功能:
this.combinedItems = this.combinedItems.sort((a, b) => {
const dateA = a.appointmentDate || a.cancelDate;
const dateB = b.appointmentDate || b.cancelDate;
return dateA - dateB
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/343784.html
