Arranging various items into a unified catalogue using Typescript

In my Angular application, I am trying to sort two arrays of different objects by date. The first object has properties appointmentId and appointmentDate, while the second object has properties cancelId and cancelDate. Currently, my code sorts the items by the appointment date only. How can I modify it to also sort by the cancellation date so that 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;
  
  // Combine both arrays and sort by appointment date
  this.combinedItems = ([]).concat(this.appointments, this.cancellations);
  this.combinedItems = this.combinedItems.sort((a, b) => new Date(a.appointmentDate) - new Date(b.appointmentDate));
  
  console.log(this.combinedItems);
});

Answer №1

Understanding the sorting priority of properties is crucial. I have arranged it in the sequence you provided, with appointmentDate being first and cancelDate following after.

forkJoin([appointments, cancellations]).subscribe(results => {

  [this.appointments, this.cancellations] = results;

  this.loading = false;

  this.combinedItems = [...this.appointments, ...this.cancellations];

  const comparisonFunction = (a: any, b: any) => {
      const compareByAppointmentDate = a.appointmentDate - b.appointmentDate;
      const compareByCancelDate = a.cancelDate - b.cancelDate;
      return compareByAppointmentDate || compareByCancelDate;
  }
   
  this.combinedItems = this.combinedItems.sort(comparisonFunction);
  console.log(this.combinedItems);

});

Answer №2

When both dates need to be used simultaneously, the sort function can be modified as follows:

this.combinedItems = this.combinedItems.sort((x, y) => {
  const firstDate = x.appointmentDate || x.cancelDate;
  const secondDate = y.appointmentDate || y.cancelDate;
  return firstDate - secondDate
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Emotion CSS to incorporate images into buttons

I'm trying to add some style to two buttons, Up and Down, by using emotion CSS but I'm having trouble. Currently, I typically style my elements within a function. Is there a way for me to accomplish this with emotion CSS? I checked out but still ...

Retrieve the component's scope within a function invoked by the [calculateCellValue] method in dxi-column

I am facing a challenge where I am unable to access the context of a component.ts from a function that I call using [calculateCellValue]="function". If I try to pass the context using .bind(this), the interactive features of the DataGrid stop working. The ...

Liferay's JavaScript bundler does not automatically remove unused node modules

Within my work on Liferay 7.3.5 and developing an Angular Portlet, I have encountered a frustrating issue. When experimenting with different modules or versions of the same module, I noticed that the final jar OSGI module contains all the modules I have in ...

Encountering a 405 HTTP error in Angular8 app when refreshing the page

Currently, I am working on a project using Angular8 and .NET Core 3.0 in Visual Studio. Everything is running smoothly except for one issue that arises when I press F5 on a page with a form. The error message that pops up reads: Failed to load resource: ...

The term 'App' is being referenced as a value when it is intended to be a type. Perhaps you meant 'typeof App'?

I am eager to master Typescript with React through hands-on experience, so I recently made the manual transition from JavaScript to TypeScript in my create-react-app. However, when working with my default testing file App.test.ts: import { render, screen ...

Exploring Angular 2's primeng Tree Component

I am currently working on an angular2 project that involves primeng. The issue I am facing is related to the tree component in primeng, which gives me an error when I try to use it. I have already executed npm install primeng --save and imported the necess ...

"Unable to convert object into a primitive value" error message appears on Internet Explorer

Currently working on a webpage using Angular 7. The code is functioning perfectly in Chrome, however, I am facing an Exception error while running it in IE: An issue arises: Can't convert object to primitive value (polyfills.ts) The source of the er ...

What steps can be taken to address the CORS problem if the endpoint does not support the OPTIONS method?

I've been developing mobile client apps to easily manage a Magento E-commerce store, utilizing Token Based authentication from this source. I've chosen to use Ionic2 as my mobile framework. However, a challenge I'm facing is that the angula ...

Issue with Progressive Web App functionality when using Angular Pre Rendering

Currently, I am working on an Angular 10 Universal project. Whenever I execute the following command: "build:ssr": "ng build --prod && ng run PROJECT:server:production && node dist/PROJECT/server/main.js", I can see th ...

Choose the initial mat-option with mat-select functionality

In my app, I have several Angular Material select dropdowns with mat-options that are updated reactively based on other values (filtering of options). Here's an example: <mat-select #selects (selectionChange)='formChanges()' [placeholder ...

Error Arises When Making Selection in PrimeNG's P-ListBox Component

Whenever I choose an item from my listbox module, I encounter an error where the value is being returned as an object instead of an array in my listbox.js file from p-listbox by PrimeNG. HTML: <p-listbox formControlName="programType" [options]="phoneT ...

Creating Swagger documentation for dynamic request and response is a process that involves documenting the various

Our API application operates dynamically using SQL-defined metadata to generate reports based on the requests it receives. When a JSON request is passed in like the examples below: { "Field1": "Value1" "GroupBy": [&qu ...

Angular 6 - Share content easily on mobile devices (IOS, Android)

After reviewing this example detailing the use of Angular 5 for copying to clipboard, I encountered issues when trying to run it on the iPhone 6s. Is there a more comprehensive solution available? ...

Strangely, the combination of BehaviorSubject, async pipe, and *ngIf in Angular is causing unexpected behavior: ngOnChanges is detecting a change that should not

I am facing an issue with two components in Angular - the Parent component fetches data from the server and the Child component displays the fetched entries as a list, but only if the list is not null or empty. The problem I am encountering can be summari ...

Prevent overlapping of range sliders in HTML and CSS

I have designed a range slider with two buttons, but they are overlapping each other. I want to ensure that they do not cross over one another - where the value of the first button should be equal to the minimum value of the second button, and the maximum ...

Karma keeps showing up as empty coverage

I've been struggling to get karma coverage to work for the past couple of days, but all I keep seeing is a blank empty page like this: https://i.sstatic.net/3Fr6I.png Check out my configuration: var path = require('path'); var webpackCon ...

Maximizing Jest's potential with multiple presets in a single configuration file/setup

Currently, the project I am working on has Jest configured and testing is functioning correctly. Here is a glimpse of the existing jest.config.js file; const ignores = [...]; const coverageIgnores = [...]; module.exports = { roots: ['<rootDir&g ...

When incorporating ng2-translate within a jhipster project, an issue arises where the property 'parser' is deemed private in the 'TranslateService' type, although it is not private in the same type

Having an issue with the Translate module while building my project using Angular-CLI as a client for Jhipster. Upgrading to ngx-translate did not resolve the problem. Error message: 'TranslateService' is not assignable to parameter of type &ap ...

Protractor encountering a session creation exception for chrome

Encountering an error while trying to execute a Protractor test in Chrome. Here is my conf.ts file: import {Config} from 'protractor' export let config: Config = { framework: 'jasmine', multiCapabilities: [ { ...

Connecting data with Angular

Recently, as part of my learning journey with Angular, I encountered an intriguing issue. While working on my code, I noticed that the error popped up in my code editor (VSCode) but not when running the code in the browser. The dilemma stemmed from settin ...