Custom sorting pipe for Angular 6

15.4k Views Asked by At

I am trying to sort my data in the ngFor loop , but my custom pipe doesnot work as intened , can anybody help me out...

  export class OrderbyLastMessagePipe implements PipeTransform {

  transform(array: Array<string>, args?: any): Array<string> {

    if (array !== undefined && array !== null && args !== '') {

      console.log('args', array);

        const direction = args === 'desc' ? 1 : -1;
        array.sort((a: any, b: any) => {

          console.log('args', a);

          if (a['lastUpdatedat'] < b['lastUpdatedat']) {
                return -1 * direction;
            } else if (a['lastUpdatedat'] > b['lastUpdatedat']) {
                return 1 * direction;
            } else {
                return 0;
            }
        });
    }
    return array;
}

My Component ng container is this , i am using two filters one for search and another for sort on specific lastupdatedat value which is the timestamp ...

 <ng-container *ngFor="let User of uLists | orderbyLastMessage:'uLists':true">         
2

There are 2 best solutions below

0
On BEST ANSWER

very similar answered here

Angular Custom Order Pipe sorting array correctly

The user search must be done with input type text, keyup event, and array.filter method.

Good luck!

1
On

Two recommendations:

  1. If you used angular CLI to generate your pipe, it's name is orderByLastMessagePipe. You can see this in your code like such:

    @Pipe({name: 'orderByLastMessagePipe'})

  2. The parameters you are passing to your pipe will always cause it to sort ascending. With angular pipes, multiple parameters are delimited by :. The orderbyLastMessage:'uLists':true" should be orderbyLastMessage:'desc' to sort descending, and orderbyLastMessage to sort ascending, or orderbyLastMessage:'asc'.

Change your template to:

<ng-container *ngFor="let User of uLists | searchUser:filterUser | orderbyLastMessagePipe:'desc'"> 

See if that fixes your sorting.

Edit

The array parameter to your pipe is obviously not an Array<string>. If you have a specific type for the objects in your array, the parameter should be typed to that Array<SomeObject>. If not, any will do Array<any>, or just any.

This answer is NOT the correct way to do sorting due to poor performance as pointed out in previous comments. Just trying to answer the specific question that is asked.