What is the best approach for arranging numbers in descending order?

I'm struggling to sort numbers from largest to smallest and need some help.

My code successfully sorted numbers with 5 digits, but not the others.

Here is a snippet of the unsorted numbers:

15366   
13070       
13069       
13068   
13067       
13066       
13065       
13064
313883
313880
313878
313876
313874
313872
313870
313869
313868  

https://i.sstatic.net/HGIt0.jpg

The correct order should be:

313883
313880
313878
313876
313874
313872
313870
313869
313868  
15366   
13070       
13069       
13068   
13067       
13066       
13065       
13064

I don't understand why it didn't sort all the numbers together?

The code template is provided below:

<ng-container *ngFor="let transfer of transferResponse.PRE">
   <ng-container *ngFor="let preptf of transfer.PREPTF">
      <tr>
         ...
         <td class="text-center">
            <a [routerLink]="['/transfers/customer-transfer-details/' + preptf.NUM]">{{preptf.NUM }} </a>
         </td>
         ...
      </tr>
   </ng-container>
</ng-container>

The interface structure is as follows:

export interface TransferResponse extends ApiResponse {
    PRE: Transfer[];
}

export interface Transfer {
    DEPO: number;
    CLER: string;
    INTITULE1: string;
    PHONE: string;
    PREPTF: {
        LABEL: string;
        TYPE: string;
        QUANTITE: number;
        STATUT: number; 
        NUM: number;
        ISIN: string;
        STATUT_LIB: string;
        REF_RBC: string;
    }[];
}

The component script looks like this:

export class OverviewTransfersComponent implements OnInit, OnDestroy {
   private unsubscribe$ = new Subject < void > ();
   currentAgency: any;
   transferResponse: TransferResponse;

   constructor(
      private service: OverviewTransfersService,
      private store: Store,
      private modalService: BsModalService,
      private router: Router
   ) {}

   ngOnInit(): void {
      this.currentAgency = this.store.selectSnapshot(AgencyState.currentAgency);
      if (this.currentAgency) {
         this.OverviewTransfers();
      }
   }

   ngOnDestroy(): void {
      this.unsubscribe$.next();
      this.unsubscribe$.complete();
   }

   OverviewTransfers(): void {
      console.log('Before the request service.OverviewTransfers()');
      this.service.OverviewTransfers().pipe(
         takeUntil(this.unsubscribe$)
      ).subscribe(res => {
         console.log('Response service.OverviewTransfers()', res);
         if (res.RETURNCODE === ApiResponseCodeEnum.Ok) {
            const transferResponse = res as TransferResponse;
            console.log('Before sorting', transferResponse);
            transferResponse.PRE.forEach(transfer => {
               transfer.PREPTF.sort((a, b) => {
                  return b.NUM - a.NUM;
               });
            });
            console.log('After sorting', transferResponse);
            this.transferResponse = transferResponse;
         }
      });
   }

}

Console Logs for Reference:

https://i.sstatic.net/qVemW.png

https://i.sstatic.net/LR6p1.png

https://i.sstatic.net/gIQmD.png

https://i.sstatic.net/JOjOF.png

Any assistance would be greatly appreciated. Thank you!

Answer №1

The issue arises from attempting to sort an array within another array.

Initially, you have an array of TransferResponse, and then try to sort the nested array PREPTF.

To resolve this, consolidate all numbers into a singular array prior to sorting.

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

What is the best way to execute an asynchronous request within a CanDeactivateFn guard in Angular?

Here's a strange question I've been grappling with lately. So, I've got this function that essentially creates a custom Alert Window to handle unsaved form data when a user tries to navigate away. It may or may not be triggered depending on ...

What is the best way to calculate the number of items in your mongoose reference with a specific field?

I am trying to calculate the number of active Workers that belong to a specific company. Here is an example scenario: const workerSchema = new Schema( { userId: { type: Types.ObjectId, ref: 'User', ...

Stacking SetIntervals on top of each other

I've been working on a project that involves using setInterval, but I'm struggling to grasp how it functions. The issue I'm encountering is that every time I invoke setInterval, the function appears to be stacking on top of one another, caus ...

What is the best way to apply a hover effect to a specific element?

Within my CSS stylesheet, I've defined the following: li.sort:hover {color: #F00;} All of my list items with the 'sort' class work as intended when the Document Object Model (DOM) is rendered. However, if I dynamically create a brand new ...

Closing iframe in Angular 4 after redirection

I am currently working on an Angular 4 application that involves integrating a third-party payment system called Tranzila. Tranzila offers a convenient integration method using an iframe, allowing users to make payments on their domain without me having to ...

Learning about subscribing and unsubscribing to Angular RxJS Subjects

I'm facing an issue with my component that retrieves updates from an API link. Even after destroying the component, the API call continues to run. I have used a subject and unsubscribed from it in an attempt to stop the call. Here is my API service me ...

Is there a method to develop an application utilizing the local web page as the interface?

Just a few days ago, I came up with the idea to create my own user-friendly "interface" for organizing and accessing some of my personal files. Having all related data, images, and links easily accessible with just a few clicks sounded very convenient to m ...

Implementing strong security measures for Angular and .Net Core APIs using Azure AD authentication and defining specific application roles

My system is a combination of Angular front end and .Net Core API back end. Both are set up as distinct Active Directory apps in the Azure Portal. As a result, both applications are protected by Azure AD. The API is exposed and interacted with by authenti ...

Tips for identifying routing to identical page in Angular 2?

In my navigation bar, I have a search function that utilizes the router to pass the query in the route and directs users to the correct component. For the search button in my navbar component, the code looks like this: onSubmit() { this.router.navigate ...

Challenges with line height in IE when adjusting font size in textarea

I'm facing an issue with adjusting the font size in a textarea using JavaScript. While it works perfectly in Firefox, there are some problems in IE. Specifically, the line-height does not change accordingly. This results in gaps between lines when the ...

Arrow functions serve as references to variables within a specific context

Is there a way to pass an arrow function as a variable in a tab? I am working with a function that looks like this: public handleLogin(data) { this.socket.send(data); [...] } This function is located within a functions tab: let tab = [this.handleLo ...

What is the fastest way to efficiently insert multiple script-generated records into PostgreSQL from a node.js environment?

On my laptop PC, I'm finding that the code snippet below, designed to insert 200,000 records into a PostgreSQL server from node.js, is running quite slow at around 17 minutes. var pg = require('pg'); var Client = pg.Client; var async = requ ...

Navigate to the chosen item in material-ui scroll bar

Currently, I have a list created using material-ui which contains numerous items and displays a scrollbar due to its size. I am looking for a way to automatically scroll to the selected item within the list. Does anyone have any suggestions on how I can a ...

Is it possible to eliminate auxiliary routes in Angular 4?

Recently, I came across an interesting scenario with two <router-outlet> tags, one with a name property. To test this, I set up the following router mapping: export const routing = [ {path:'', pathMatch:'full', component:E ...

A guide on utilizing webpack for deploying an Express and React application

I am currently working on a project that utilizes webpack-dev-server for development. My goal is to deploy the application using an express server that serves content through Pug templates or the static HTML page generated by HtmlWebpackPlugin during produ ...

I'm having trouble with installing nx as it keeps showing the error message 'Platform Dependency for NX is Missing.'

I encountered an issue when running npm install: $ npm i npm WARN deprecated @babel/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b5b475e4c4245065b59445b44584a470648474a5858065b59445b4e595f424e586b1c051a13051d">[email  ...

Tips for adjusting card content to fit its size in material ui?

I'm looking to implement Material UI cards in a grid layout, each containing a Highcharts chart as shown in this demo. However, I'm facing an issue where the content does not adjust properly when the card size is fixed. How can I resolve this? A ...

What is the process of performing numerical calculations using jQuery?

I need to deduct certain input values from the total price. Here's the code snippet: $('.calculate-resterend').click(function(e) { e.preventDefault(); var contant = $('.checkout-contant').val(); var pin = $('.che ...

The Javascript executor in Selenium is delivering a null value

My JavaScript code is causing some issues when executed with Selenium's JavascriptExecutor. Strangely, the code returns null through Selenium but a value in Firefox developer console. function temp(){ var attribute = jQuery(jQuery("[name='q& ...

The syntax in JavaScript of (0, fn)(args) is used to call

I came across an interesting piece of JavaScript code in Google's codebase that I wanted to discuss: var myVar = function...; (0, myVar)(args); Do you know what the significance of this syntax is? I'm struggling to see the difference between ( ...