Created
March 28, 2016 03:06
-
-
Save chandermani/e721cab947440d6a3863 to your computer and use it in GitHub Desktop.
orderBy pipe in Angular2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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]); | |
} | |
} | |
} |
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
I just switched it to take one string argument "field" since I needed only to sort by one attribute, only.
Used it this way:
Where "orderByModel" is dynamically changing.
Here is the updated pipe: