0

I have created the following pipe:

@Pipe({
  name: 'orderBy',
  pure: false
})
export class OrderByPipe implements PipeTransform {

  transform(array: Array<any>, orderProperty: string): Array<any> {
    array.sort((a: any, b: any) => {
      if (a[orderProperty] < b[orderProperty]) {
        return -1;
      } else if (a[orderProperty] > b[orderProperty]) {
        return 1;
      } else {
        return 0;
      }
    });
    return array;
  }

}

Usage:

<div class="patient-box level-1" draggable="true" *ngFor="let bed of (beds | orderBy: order)" (dragstart)="onDrag($event, patient)">

I understand that impure pipes update very often. What I don't understand is that the order of my array changes even though no data has changed. I have 3 properties that the objects can be ordered by, and it only happens with two of them for some reason, and it's the same 3 objects that are constantly changing positions.

I know it's probably not easy to figure out what is wrong with the information given, but I was hoping someone could have a clue. If it's any help, the three objects that are changing positions have the same value in the property that the array is being ordered by, although there are other objects with that value too that are not moving.

Jesper
  • 2,644
  • 4
  • 30
  • 65
  • 2
    1. You shouldn't use such a pipe, for reasons explained in the docs. 2. A pipe shouldn't mutate its input. It should create a sorted copy of the array. 3. The sort is not necessarily stable (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) – JB Nizet Aug 29 '17 at 18:16
  • @JBNizet The problem is that I need it do update whenever a property in one of the objects in the array changes. How to do that without an impure pipe? – Jesper Aug 29 '17 at 18:25
  • 2
    @Jesper Multiple possibilities: A custom setter for the array. Observables. A custom function. A pipe is just syntax sugar and is supposed to be used for trivial manipulation of output, such as formatting etc. – Lazar Ljubenović Aug 29 '17 at 18:30
  • Because of the possible performance issues, Angular doc discourages the use of pipes for filtering and sorting. More [here](https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe) – BogdanC Aug 29 '17 at 19:35

0 Answers0