After the assignment, TypeScript reordered the elements of the array

Dealing with an array of objects for use in a ngFor loop has presented a challenge. The issue arises when the order that was initially set for the array changes unexpectedly due to JavaScript manipulation.

Originally, the array is ordered as expected when I set a breakpoint before the console.log:

Array with the correct order

However, upon logging the array, the element at position 8 seems to be shifted to position 0, causing the ngFor loop to interpret it in this revised order:

Revised array

The construction of the array is demonstrated in the following code snippet:

this.recommendations.forEach(recommendation => {
        recommendation.Journeys.forEach(function (journey, indexJour) {
            journey.Segments.forEach(function (segment, indexSeg) {
                segment.Flights.forEach(function (flight, index) {
                    const newFlight: FlightAvailabityByPrice = {
                        // flight details here
                    };

                    if (!(journey.JourneyId in newGroup)) {
                        // logic here
                    }

                    tempFlights.push(newFlight);
                });
            });
        });

        const newRecommendation: RecommendationList = {
            flights : tempFlights
        };
        tempFlights = [];
        tempRecommendation.push(newRecommendation);
        tempGroups.push(newGroup);
        newGroup = {};
    });
    this.rowGroups = tempGroups;
    this.flightsInfo = tempRecommendation;

In the HTML markup, the table component from PrimeNG used for the body is shown below:

<ng-template pTemplate="body" let-recoInfo let-index="rowIndex">
                            <tr class="ui-widget-header" *ngIf="rowGroups[i][recoInfo.journeyId].index === index">
                                <td colspan="14">
                                    <i class="fa fa-plane" [ngClass]="{'departure': recoInfo.journeyId === 1, 'arrival': recoInfo.journeyId !== 1}"></i>
                                    <span style="font-weight:bold">{{recoInfo.journeyId === 1 ? 'SELECT_DEPARTURE' : 'SELECT_ARRIVAL'}}</span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <mz-checkbox-container>
                                        // checkbox input
                                    </mz-checkbox-container>
                                </td>
                                <td>
                                    <img src="assets/images/flight_companies/{{recoInfo.company}}.png" alt="{{recoInfo.company}}">
                                </td>
                                <td>{{recoInfo.system}}</td>
                                // more table rows here
                            </tr>
                        </ng-template>

Any assistance provided will be greatly appreciated!

Answer №1

It's interesting how separating nested loops into subroutines can simplify the logic, making it easier to understand. In a pinch though, sorting by segmentId could be a quick fix before refactoring.

 tempFlights.sort(function (a, b) {
 return a.segmentId - b.segmentId;
 })

I found this approach in the official documentation here

I hope this solution suits your needs and best of luck with your project!!

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

AG Grid is displaying improperly within Angular

I am facing an issue with using ag-grid in my project. The output is not as expected and I am unsure of what the problem might be. Here is a snippet of my HTML code: <p>user-access works!</p> <ag-grid-angular style="width: 500px; height: 50 ...

Tips for testing an Angular service method that returns a JSON object

I have a service in Angular that processes JSON input and returns JSON output after some operations. My positive test case for this service is failing consistently. I suspect the reason for this failure might be: Expected Result : [ Object({ key: &apos ...

Dealing with the 'UNIFIED_TEST_PLATFORM' issue while trying to compile an Ionic android app that utilizes tesseract.js and capacitor core

I recently set up an Ionic Angular project and integrated Capacitor to access native code functionalities. My project utilizes tesseract.js, as well as Capacitor core and camera plugins. However, I encountered an error while building the Android project: ...

Parent Component in Angular 2 Fails to Refresh Upon Observable Update

I have been utilizing an Observable service to facilitate data coordination among components. Specifically, I am attempting to utilize it for managing the visibility of various HTML elements within my application. Currently, when I toggle the behavior sub ...

In Typescript 12, the process of creating a Bootstrap popup that waits for the user to click on a value entered in

Greetings! I am currently working with Angular TypeScript 12 and I am attempting to trigger a Bootstrap modal popup when I enter a code in the input field and press enter. However, the issue is that the popup is always displayed even without typing anythin ...

Error: Module not found - Issue with importing SVG files in NextJS

Currently, I am utilizing the babel plugin inline-react-svg to import inline SVGs in NextJS. Here is a snippet from my .babelrc configuration file: { "presets": ["next/babel"], "plugins": [ "inline-react-svg" ...

Tips for managing Angular modules post-splitting and publishing on npm

Currently, I am in the process of developing an Angular application. To ensure reusability and prevent duplication of components and services in another application, I have divided the app into modules and deployed them on a private npm and git server. No ...

Angular is unable to load additional routes

While working on building a web application with Angular 11, I encountered an issue with routing. When navigating from the initial route ( { path: '', component: HomeComponent } ) to other routes, everything functions as expected. However, when ...

Intellisense capabilities within the Gruntfile.js

Is it a feasible option to enable intellisense functionality within a Gruntfile? Given that 'grunt' is not defined globally but serves as a parameter in the Gruntfile, VSCode may interpret it as an unspecified function parameter 'any'. ...

Is your Express router failing to handle post requests properly?

I've set up my development environment using angular-cli and webpack, with the following configuration in package.json: "dependencies": { "@angular/common": "^4.0.0", "@angular/compiler": "^4.0.0", "@angular/core": "^4.0.0", "@angular ...

An error occurred while trying to add a property to an array because the object is not extensible: TypeError -

In my code, there is an object named curNode with the following structure: { "name": "CAMPAIGN", "attributes": {}, "children": [] } I am attempting to add a new node to the object like this: curNode!.children!.push({ name: newNodeName, ...

How can I achieve hover and click effects on an echarts sunburst chart in Angular using programming techniques?

Could I create hover and click effects programmatically on an Echarts sunburst chart using Angular? For example, can I trigger the sunburst click or hover effect from a custom function in my TypeScript file like this: customFunction(labelName: string): v ...

Is there a way to prevent this React function from continually re-rendering?

I recently created a small project on Codesandbox using React. The project involves a spaceship that should move around the screen based on arrow key inputs. I have implemented a function that detects key presses, specifically arrow keys, and updates the ...

Implementing the Infinite Scroll feature with 'react-infinite-scroll-component' on local JSON data: A step-by-step guide

Currently experimenting with frontEnd development, I have incorporated the 'react-infinite-scroll-component' as a dependency. My goal is to apply this effect to my local Json data without relying on any API calls at this stage. I'm encounter ...

Specialized type for extra restriction on enum matching

In my current project, I am dealing with two enums named SourceEnum and TargetEnum. Each enum has a corresponding function that is called with specific parameters based on the enum value. The expected parameter types are defined by the type mappings Source ...

Incorporating CodeMirror into Angular2 using TypeScript

I've been working on integrating a CodeMirror editor into an Angular2 project, but I'm encountering some issues with the instantiation of the editor. Here is my code snippet: editor.component.ts import {Component} from 'angular2/core' ...

Clicking on an Angular routerLink that points to the current route does not function unless the page is re

Currently, I am working on an E-commerce project. In the shop page, when a user clicks on the "View More" button for a product, I redirect them to the product details page with the specific product id. <a [routerLink]="['/product-details' ...

What is the process for including headers while establishing a connection to a websocket?

After configuring a websocket topic using Spring websocket on the server side, we implemented the client side with Stomp.js to subscribe to it. Everything was functioning correctly when connecting directly to the websocket service. However, we decided to i ...

Using React JS to Sort an Array Based on a Specific String

Here I am again, this time dealing with reactjs. I have a json object containing two "rows", labeled as Description and ubication. My goal is to filter the array based on the Description field. How can I achieve this? The description is in text format, f ...

Expanding the base class and incorporating a new interface

(Here is an example written using Typescript, but it applies to other cases as well) class IMyInterface { doC:(any) => any; } class Common { commonProperty:any; doA() { } doB() { } } class ClassA extends Common {} class Clas ...