Arranging arrays of various types in typescript

I need help sorting parameters in my TypeScript model. Here is a snippet of my model:

export class DataModel {
   ID: String
   point1: Point
   point2 : Point
   point3: Point
   AnotherPoint1: AnotherPoint[]
   AnotherPoint2: AnotherPoint[]
   AnotherPoint3: AnotherPoint[]
}

export class Point {
 Name: String
 Timestamp: String
}

export class AnotherPoint {
 Name: String
 Timestamp: String
}

In my component, I have a sorting function that currently sorts Points based on their names and timestamps. Now, I also need to sort AnotherPoints along with the Points. How can I achieve this?

Answer №1

To enhance the functionality, I propose creating two auxiliary functions to compare two Points and two arrays of AnotherPoints separately. The comparison would be based on element-by-element analysis, halting once a pair of elements fails to match with each other.

function comparePoints(pA: Point | AnotherPoint, pB: Point | AnotherPoint)
{
    const pointA = pA.Name.toLowerCase();
    const pointB = pB.Name.toLowerCase();
    if (pointA < pointB ) {
        return -1;
    }
    if (pointA > pointB ) {
        return 1;
    }
    const timeA = pA.Timestamp;
    const timeB = pB.Timestamp;
    return Service.compareDate(new Date(timeA), new Date(timeB));
}

function comparePointArrays(arrayA: AnotherPoint[], arrayB: AnotherPoint[])
{
    const len = Math.min(arrayA.length, arrayB.length);
    for (let i = 0; i < len; ++i)
    {
        const result = comparePoints(arrayA[i], arrayB[i]);
        if (result !== 0) {
            return result;
        }
    }
    return 0;
}

Subsequently, the sorting procedure can be refined by incorporating these new comparator functions:

private sortByNameAndID(dataModel: DataModel[]): DataModel[] {
    return dataModel.sort(function (a, b) {
        return comparePoints(a.point1, b.point1) ||
            comparePoints(a.point2, b.point2) ||
            comparePoints(a.point3, b.point3) ||
            comparePointArrays(a.AnotherPoint1, b.AnotherPoint1) ||
            comparePointArrays(a.AnotherPoint2, b.AnotherPoint2) ||
            comparePointArrays(a.AnotherPoint3, b.AnotherPoint3);
    });
}

It is essential to note that the || operator executes the operation on the right only if the preceding operation yields a falsy (0) outcome, implying that comparisons cease as soon as there is a non-zero result.

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

Universal customization for Material-UI Select

I am attempting to customize the appearance of a select component within a React project using MUI 5. Specifically, I want to modify the border size and color when the select component is in focus. While other components can be styled globally using styleO ...

Updating the default value for react-i18next (stored in localstorage)

When utilizing a backend and language detector, an issue arises: The localstorage contains the key I18nextLng with the value en-US. How can we set the default value to be I18nextLng with the value En? init and other settings are as per the default docume ...

Ways to verify a component that expands from a base component using ng-mocks

In my code, I have a CakeItemContainerComponent that extends ItemContainerComponent and I am attempting to test it using ng-mocks. Here is what I'm trying to accomplish: @Component({ selector: 'app-item-container', template: '&apos ...

Guide on obtaining the Parent hierarchy within the Tree View component

Hello! I am working with a tree object that has parent and nested children, displayed with checkboxes. When a child is checked, I need to retrieve the names of the parent and grandparent up to the entire hierarchy. Below is my JSON data: { [ ...

Modifying the calendar from a 7-day week to a 5-day week

I am currently in the process of developing a 7-day calendar (Sunday to Saturday) which is functioning well. However, I am interested in adding an option to switch it to a 5-day calendar (Monday to Friday). I was wondering if there is a way to modify the e ...

Issue: A request is not pending for flushing during the testing of an AngularJs service

As a beginner in AngularJs, I am currently working on my first unit test. In order to test the service I created, I wrote a test that simply returns a single Json object. However, whenever I run the test, I encounter the error mentioned in the title. I am ...

Discovering the way to retrieve information from a service in Angular post-subscription

This is the service I provide: getDataDetails(id: any) { this.dataDocumment = this.afs.doc('data/' + id); return this.data = this.dataDocumment.valueChanges().subscribe(res =>{ this.data = res; console.log(this.data); ...

Linux web server blocking requests across different domains, even with correct Access-Control-Allow-Origin headers set

I am facing an issue with my Ubuntu web server running a React app. There are two files on the server that handle requests made by the website, but for some reason, clients are unable to make requests to the server. Server.js: const express = require(&apos ...

What situations warrant the use of unescaped !{} in pug for string interpolation?

Is there a practical application for utilizing !{} - string interpolation in an unescaped format, despite the potential risks associated with its use? I have reviewed the information provided at these sources: Using !{ } and #{ } interpolation in a jade ...

Tips for sending data to CSS in Angular

I have an Angular application where I need to calculate the width of an element and store it in a variable called finalposition. Then, I want to move this element to the left by (finalposition)px when hovering over it. How can I achieve this styling effect ...

implement adding a division element to the DOM using the append

I am facing an issue with this particular code. The intended functionality is to create multiple divs in a loop, but it seems to be dysfunctional at the moment. Upon clicking, only one div appears and subsequent clicks don't trigger any response. < ...

Checking conditions sequentially in Angular

I have a unique use case that requires me to verify certain conditions. If one condition fails, I should not proceed to the next one. Instead, based on the failed condition, I need to display a dialog with a title and description explaining what went wrong ...

What causes TypeScript to narrow the type when a return statement is present, but not when it is absent?

I am facing an issue with this script: type Input = string function util(input: Input) { return input } function main(input: Input | null) { const isNull = input === null if (isNull) { return 'empty string' } inpu ...

Retrieve identification details from a button within an ion-item located in an ion-list

<ion-list> <ion-item-group *ngFor="let group of groupedContacts"> <ion-item-divider color="light">{{group.letter}}</ion-item-divider> <ion-item *ngFor="let contact of group.contacts" class="contactlist" style="cl ...

Ways to display a jQuery alert when navigating on a webpage

I am looking to enhance my page navigation by implementing a jQuery confirmation message with 'Yes' and 'No' buttons. This way, when I navigate from one page to another, I can decide whether to proceed or stay on the current page. Inst ...

Having trouble with looping the CSS background using JavaScript in CodePen

Can someone help me with looping through CSS background images? Why is the background not changing in this code example: http://codepen.io/anon/pen/dGKYaJ const bg = $('.background').css('background-image'); let currentBackground = 0; ...

Retrieving a string from a variable, which was imported from JS, to use as a key within

Is it possible to assign a variable as the key of an object in JavaScript? I have imported constants from a 'definitions.js' file and I need to use these constants as keys: import * as cons from '../scripts/definitions.js' export def ...

Ways to position an image in the middle of a Div

I am currently working with PHP and Smarty, attempting to display a slideshow's images in the center of a specific div, but I am encountering difficulties achieving this. Below you will find the code snippet. Can anyone help me figure out what I migh ...

Unable to store loop information fetched from api into a JSON file

I'm currently facing an issue with my code where I am trying to save the results from looping through an API into a JSON file using writeFileSync. Here is the code snippet in question: function processRarity(limit) { var resultJson = []; for ( ...

TypeScript throws an error if trying to access an Object variable using a String

While the code below is functioning as intended, I am encountering an error in the VS Code Typescript compiler stating that "Type 'String' cannot be used as an index type". Oddly enough, using a string literal instead of a variable like ...