javascript 如何将数字从大到小排序?

jvidinwx  于 2023-03-16  发布在  Java
关注(0)|答案(1)|浏览(163)

我正试着把数字从大到小排序,但我没能成功。
我的代码对5位数的数字进行了完美的排序,但对其余的数字却没有。
下面是一个例子:

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

结果应为:

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

我不明白为什么它不一次把所有的东西都分类?
模板

<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>

介面

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;
    }[];
}

成分

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;
         }
      });
   }

}

控制台日志

响应服务。概述Transfers()

排序服务之前。OverviewTransfers()

排序服务后。OverviewTransfers()

预先感谢你的帮助。

t1qtbnec

t1qtbnec1#

它不起作用,因为您是在数组内部对数组进行排序。
首先,您有一个TransferResponse数组,您要在该数组上迭代排序子数组PREPTF
如果您想这样做,您需要将所有数字重新组合到一个数组中,然后对它们进行排序。

相关问题