Skip to content

Instantly share code, notes, and snippets.

@chandermani
Created March 28, 2016 03:06
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chandermani/e721cab947440d6a3863 to your computer and use it in GitHub Desktop.
Save chandermani/e721cab947440d6a3863 to your computer and use it in GitHub Desktop.
orderBy pipe in Angular2
@Pipe({
name: 'orderBy'
})
export class OrderByPipe {
transform(value: Array<any>, args: any[]): any {
let field: string = args[0];
if(value==null) {
return null;
}
if (field.startsWith("-")) {
field = field.substring(1);
if (typeof value[field] === 'string' || value[field] instanceof String) {
return [...value].sort((a, b) => b[field].localeCompare(a[field]));
}
return [...value].sort((a, b) => b[field] - a[field]);
}
else {
if (typeof value[field] === 'string' || value[field] instanceof String) {
return [...value].sort((a, b) => -b[field].localeCompare(a[field]));
}
return [...value].sort((a, b) => a[field] - b[field]);
}
}
}
@tzgued
Copy link

tzgued commented Apr 12, 2017

not working. doesn't throw errors either

@FedC
Copy link

FedC commented Apr 25, 2017

I just switched it to take one string argument "field" since I needed only to sort by one attribute, only.

Used it this way:

<li *ngFor="let item of collection | orderBy: orderByModel" > ... </li>

Where "orderByModel" is dynamically changing.

Here is the updated pipe:

import { Pipe, PipeTransform }   from '@angular/core';

@Pipe({name: 'orderBy'})
export class orderByPipe implements PipeTransform {
  transform(value: Array<any>, field: string): any {
    if(value == null) {
      return null;
    }
    if (field.startsWith("-")) {
      field = field.substring(1);
      if (typeof value[field] === 'string' || value[field] instanceof String) {
        return [...value].sort((a, b) => b[field].localeCompare(a[field]));
      }
      return [...value].sort((a, b) => b[field] - a[field]);
    }
    else {
      if (typeof value[field] === 'string' || value[field] instanceof String) {
        return [...value].sort((a, b) => -b[field].localeCompare(a[field]));
      }
      return [...value].sort((a, b) => a[field] - b[field]);
    }
  }
}

@kak00n
Copy link

kak00n commented Jun 12, 2018

The pipe works fine with the last change. Thanks!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment