I have 2 arrays of different objects that I'd like to sort by date in my Angular application.
Object 1:
appointmentId: number, appointmentDate: Date
Object 2:
cancelId: number, cancelDate: Date
The following code sorts by the appointment date, how can I sort by the cancellation data at the same time so I have a combined sorted list?
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);
});
CodePudding user response:
You should know which property has a "higher" priority in sorting, i put it to be in the order that you gave. First appointmentDate, then cancelDate.
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);
});
CodePudding user response:
if you want to use both dates at the same time, you can change sort function like this:
this.combinedItems = this.combinedItems.sort((a, b) => {
const dateA = a.appointmentDate || a.cancelDate;
const dateB = b.appointmentDate || b.cancelDate;
return dateA - dateB
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>