为什么我无法多次排序?

问题描述 投票:0回答:1

所以我试图对数据数组进行大约 4 次排序,以便在 4 个不同的地方使用。我可能可以为后端存钱,但我宁愿这样。

我似乎遇到了一个问题,似乎只有一种方法有效。像这样 这是组件



export class xService {
  comp$: Observable<any[]> | undefined;
  c1 = new Array();
cp1 = new Array();
at_b3 = new Array();
at_b = new Array();
at_b2 = new Array();

  constructor(public a_s: AServ, private db: AngularFireDatabase) {

    this.comp$ = this.a_s.xc$.pipe(switchMap((x) => {
      return this.db.list('people/'+x).valueChanges();   
      }));

      this.comp$.subscribe({next: (value) => {
this.c1 = value[0];
this.cp1 = value[0].users;
this.at_b3 = value[0].users;

this.a_s.statsa.push(value[0].users);

  this.at_b = this.cp1.sort((a: any, b: any) => Number(a.stats[0].day_off) - Number(b.stats[0].day_off)).reverse();
  this.at_b2 = this.cp1.sort((a: any, b: any) => Number(a.stats[0].places_went) - Number(b.stats[0].places_went)).reverse();
  
  console.log(this.at_b)
  console.log(this.at_b2)


      }
    });


   }
}

这部分是问题


  this.at_b = this.cp1.sort((a: any, b: any) => Number(a.stats[0].day_off) - Number(b.stats[0].day_off)).reverse();
  this.at_b2 = this.cp1.sort((a: any, b: any) => Number(a.stats[0].places_went) - Number(b.stats[0].places_went)).reverse();

当我尝试渲染或使用控制台日志时。我无法获得 2 个不同的数组,但我得到的是同一个数组。

arrays angular typescript sorting
1个回答
0
投票

您需要在排序之前创建数组的副本:

export class xService {
  comp$: Observable<any[]> | undefined;
  c1 = new Array();
  cp1 = new Array();
  at_b3 = new Array();
  at_b = new Array();
  at_b2 = new Array();

  constructor(public a_s: AServ, private db: AngularFireDatabase) {
    this.comp$ = this.a_s.xc$.pipe(
      switchMap((x) => {
        return this.db.list("people/" + x).valueChanges();
      })
    );

    this.comp$.subscribe({
      next: (value) => {
        this.c1 = value[0];
        this.cp1 = value[0].users;
        this.at_b3 = value[0].users;

        this.a_s.statsa.push(value[0].users);

        this.at_b = [...this.cp1]
          .sort(
            (a: any, b: any) =>
              Number(a.stats[0].day_off) - Number(b.stats[0].day_off)
          )
          .reverse();
        this.at_b2 = [...this.cp1]
          .sort(
            (a: any, b: any) =>
              Number(a.stats[0].places_went) - Number(b.stats[0].places_went)
          )
          .reverse();

        console.log(this.at_b);
        console.log(this.at_b2);
      },
    });
  }
}

© www.soinside.com 2019 - 2024. All rights reserved.