0

I have a custom pipe that orders an array of objects by a prop that is of type number.

Template where pipe is being used

<div *ngFor="let product of products | orderBy:'price'">

OrderByPipe

export class OrderByPipe  implements PipeTransform {
transform(array: any[], field: string): any[] {
array.sort((a: any, b: any) => {
  if (a[field] < b[field]) {
    return -1;
  } else if (a[field] > b[field]) {
    return 1;
  } else {
    return 0;
  }
});
return array;
}
}

The pipe seems to work for smaller arrays and when I use forEach to loop through each item. However when I console the array at the end and when it is returned in the template, the array is still out of order.

I am not entirely sure what might be causing this, thanks.

1
  • Pipe creates a new array by ordering your existing array, after displaying ordered array it doesn't exist anymore. If you want to have the array ordered, create a service which orders an array. Commented Nov 20, 2018 at 8:28

2 Answers 2

2

Maybe you dont need a pipe at all and you need a service ,in your component

originalProducts;
orderedProducts;

ngOnInit() {
    this.getProducts();
}

getProducts() {
  this.productsService.getProducts()
    .subscribe((data) => {
    this.originalProducts = data;
    this.sortBy('price');  
  });
}

sortBy(field: string) {
    
        this.originalProducts.sort((a: any, b: any) => {
            if (a[field] < b[field]) {
                return -1;
            } else if (a[field] > b[field]) {
                return 1;
            } else {
                return 0;
            }
        });
        this.orderedProducts = this.originalProducts;
}

In your template

<div *ngFor="let product of orderedProducts">

And if your list is too long then use pagination.

If still you have trouble, use lodash.

Sign up to request clarification or add additional context in comments.

1 Comment

but this doesn't sort string having numbers correctly.Can you suggest solution for that.
-1

What are the contents of the arrays? IF they are objects (which seems likely), then you will need to implement a comparator - a function that can compare two instances of those objects. The less-than (<) and greater-than (>) operators may not be doing what you expect or desire.

1 Comment

They are objects but the fields of those objects is what is being compared, in this case prices e.g 42, 35 etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.