Angular 7 Table Reusable Sorting Pipe

In this blog, you will learn how to make reusable sorting pipes for Angular components. With the use of Angular pipes you make custom pipes and sort the array and array of objects.
  1. import { Pipe, PipeTransform } from '@angular/core';  
  2.   
  3. @Pipe({  
  4.   name: 'tableSort',  
  5.   pure:false,  
  6. })  
  7. export class TableSortPipe implements PipeTransform {  
  8.   
  9.   transform(value: any[], direcion: string, prop?: string): any {  
  10.     if (!value) {  
  11.       return [];  
  12.     }  
  13.     if (!direcion || !prop) {  
  14.       return value  
  15.     }  
  16.     if (value.length > 0) {  
  17.       const _direction = direcion === 'asc' ? -1 : 1,  
  18.         _isArr = Array.isArray(value),  
  19.         _type = typeof value[0],  
  20.         _flag = _isArr && _type === 'object' ? true : _isArr && _type !== 'object' ? false : true;  
  21.       value.sort((a, b) => {  
  22.         a = _flag ? a[prop] : a;  
  23.         b = _flag ? b[prop] : b;  
  24.         if (typeof a === 'string') {  
  25.           return a > b ? -1 * _direction : 1 * _direction;  
  26.         } else if (typeof a === 'number') {  
  27.           return a - b > 0 ? -1 * _direction : 1 * _direction;  
  28.         }  
  29.       });  
  30.     }  
  31.     return value;  
  32.   }  
  33.   
  34. }  
In this above implementation, you have to pass direction and prop as parameters, you can see prop as an optional parameter. You have to pass the key of object when you want to sort the array of objects. Make sure your pure should be false in your pipe meta data configuration.
 
With you use pure false configuration angular will keep the sorting order even if you add new items into the array.
 
So you can use this pipe to sort array and array of objects.
 
Let me know if you're facing any issue related to this.
  
Cheers!!.