离子3-通过另一个阵列管道对阵列进行排序?

时间:2018-12-30 13:10:49

标签: arrays sorting ionic-framework ionic3 pipe

我需要一个离子管3,该离子管使用Array1按ID对OrderArray进行排序。

HTML:

< ng-container *ngFor="let item of items | sortBy : ‘id’ >

Array1

[
  {“id”: 1,“title”: “Post-1”,“thumb”: “post1.png”},    
  {“id”: 2,“title”: “Post-2”,“thumb”: “post2.png”},    
  {“id”: 3,“title”: “Post-3”,“thumb”: “post3.png”},    
  {“id”: 4,“title”: “Post-4”,“thumb”: “post4.png”},    
  {“id”: 5,“title”: “Post-5”,“thumb”: “post5.png”}
]

OrderArray

[3, 5, 2, 4, 1]

我需要的结果是:

[
  {“id”: 3,“title”: “Post-3”,“thumb”: “post3.png”},    
  {“id”: 5,“title”: “Post-5”,“thumb”: “post5.png”},    
  {“id”: 2,“title”: “Post-2”,“thumb”: “post2.png”},    
  {“id”: 4,“title”: “Post-4”,“thumb”: “post4.png”},    
  {“id”: 1,“title”: “Post-1”,“thumb”: “post1.png”},
]

希望我会找到帮助的人,我尝试了很多但没有成功。

谢谢

1 个答案:

答案 0 :(得分:0)

解决方案是:

@Pipe({name: “sortBy”})
export class SortPipe {
transform(array: Array, args: string): Array {
// OrderArray
let sequence = [3, 5, 2, 4, 1];
if (array !== undefined) {
array.sort( function (a, b) {
var A = a[args], B = b[args];

  if (sequence.indexOf(A) < sequence.indexOf(B)) {
    return 1;
  } else {
    return -1;
  }
  
});
}
console.log(array);
return array;
}
}