TypeScript中的排序数组(离子)

时间:2019-06-07 13:10:10

标签: angular typescript ionic-framework

我正在尝试按ID对数组进行排序。但是,当我使用sort()方法时,什么也没有发生。

products.sort(function (a, b) {
  return a.id - b.id;
});

我该如何解决?

我的尝试

constructor(private pokemonService: PokemonService, private typeColorFactory: TypeColorFactoryService, private screenOrientation: ScreenOrientation) {
    this.pokemonService.getPokemons(1).subscribe(
      res => {
        console.log(res);

        this.pokemons = res;
        this.pokemons.sort((a, b): Pokemon => {
          if (a.id < b.id) return -1;
          if (a.id > b.id) return 1;
          return 0;
        });
        console.log(this.pokemons);
      },
      err => {
        console.log('HTTP Error', err);
      }
    );
  }

数组始终保持不变!我不知道这是否重要,但是当我在排序中console.log()时,它不会记录任何内容(尽管不知道是否可能)。

型号:

  

pastebin.com/FLTiZPSA

数据:

  

data

更新:

const products=[
  {'id':'1','name':'A'},
  {'id':'3','name':'C'},
  {'id':'4','name':'D'},
  {'id':'2','name':'B'},
];
products.sort((a,b)=> {
  console.log("test");
  return a.id-b.id;
});
this.pokemons.sort((a,b) => {
  console.log("test");
  return a.id-b.id;
});

products.sort()确实记录“测试”。

this.pokemons.sort()不会记录“测试”。

链接到this.pokemonService:https://pastebin.com/raWJ9isP

3 个答案:

答案 0 :(得分:0)

以下应该有效:

const products=[
  {'id':'1','name':'A'},
  {'id':'3','name':'C'},
  {'id':'4','name':'D'},
  {'id':'2','name':'B'},
];

console.log(products);

products.sort((a,b)=> a.id-b.id);

console.log(products);

这将导致排序数组:

[[object Object] {
  id: "1",
  name: "A"
}, [object Object] {
  id: "2",
  name: "B"
}, [object Object] {
  id: "3",
  name: "C"
}, [object Object] {
  id: "4",
  name: "D"
}]

答案 1 :(得分:0)

现在尝试这个。

this.lstClients = this.lstClients.sort(function (a, b) {
              if (a.id < b.id) { return -1; }
              if (a.id > b.id) { return 1; }
              return 0;
});

答案 2 :(得分:0)

在 cmd/终端中运行以下命令:

1. install npm install ngx-sortable app.module.ts import
2. import { NgxSortableModule } from 'ngx-sortable'
3. @NgModule({
  imports: [
    ...,
    NgxSortableModule
  ],
  ...
})

然后在您的网格表编写的html代码中,如下所示:

<ion-col data-column="id" (click)="SortData('id')" [ngClass]="{'asc': sortColumn == 'id' && sortOrder == 'asc', 'desc': sortColumn == 'id' && sortOrder == 'asc'}">
enter code here

In .ts file

sortOrder: string = 'asc';
  sortColumn = 'eq_id';
  
  constructor() {}

    SortData(col: string): void {
    if (this.sortColumn == col) {
      if (this.sortOrder == 'asc')
        this.sortOrder = 'desc';
      else
        this.sortOrder = 'asc';
    }
    else {
      this.sortColumn = col;
      this.sortOrder = 'asc';
    }
    this.Location = this.Location.sort((a, b) => {
      if (a[col] < b[col]){
        return this.sortOrder == 'asc' ? 1 : -1;
      }
      if (a[col] > b[col])
      {
        return this.sortOrder == 'asc' ? -1 : 1;
      }
      return 0;
    })
  }