Search code examples
angularangular-pipe

Angular 4 - Pipe Orderby Multiple Fields


In Angular 4 I have list like below:

[{first: 'Peter', last: 'Smith'}
{first: 'John', last: 'Smith'},
{first: 'Tony', last: 'Hornet'},
{first: 'Sarah', last: 'Hornet'}]

I need a pipe which will sort the names by last then sort by first. Does anyone know how to best do this?


Solution

  • Edit: following @JBNizet's comment, created a pipe is actually not the preferred way to go if you have many objects, due to performance reasons. (https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe)

    So if you've got many objects, you could filter them in your ts code, not in template.

    array.sort((a: any, b: any) => {
      if (!a.last.localeCompare(b.last)) 
      {
        return a.first.localeCompare(b.first);
      }
      return a.last.localeCompare(b.last);
    });
    

    Original answer

    Creating a pipe is indeed a good solution

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'sortwithName'
    })
    export class SortPipe implements PipeTransform {
    
      transform(array: any[], field: string): any[] {
        array.sort((a: any, b: any) => {
          if (!a.last.localeCompare(b.last)) 
          {
            return a.first.localeCompare(b.first);
          }
          return a.last.localeCompare(b.last);
        });
        return array;
      }
    
    }
    

    https://stackblitz.com/edit/angular-filter-1svqdn?file=app/sortFilterPipe.ts