Skip to content

Instantly share code, notes, and snippets.

@chandermani
Created March 28, 2016 03:06
Show Gist options
  • 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]);
}
}
}
@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