Created
January 23, 2016 11:22
-
-
Save nmai/087d213655ecd3bb292d to your computer and use it in GitHub Desktop.
Transforms arrays with ordering by date
This file contains 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
/* Posted by @nmai | |
* Original credits go to Vlado Tesanovic | |
* | |
* See his Stack Overflow answer + Plunkr example at | |
* -> http://stackoverflow.com/a/34528168/1146881 | |
* | |
* Example usage, sorting by the "date" property: | |
* <li *ngFor="#item of array | arraySort:'-date'">{{item.name}} {{item.date | date:'medium' }}</li> | |
* | |
* Change the direction by using + instead of - in the arraySort arguments | |
*/ | |
import { Pipe, bind } from 'angular2/core' | |
@Pipe({ | |
name: 'arraySort' | |
}) | |
export class ArraySortPipe { | |
transform(array: Array<string>, args: string): Array<string> { | |
if (typeof args[0] === 'undefined') { | |
return array | |
} | |
let direction = args[0][0] | |
let column = args[0].slice(1) | |
array.sort((a: any, b: any) => { | |
let left = Number(new Date(a[column])) | |
let right = Number(new Date(b[column])) | |
return (direction === '-') ? right - left : left - right | |
}) | |
return array | |
} | |
} | |
export var arraySortPipeInjectables: Array<string> = [ | |
bind(ArraySortPipe).toValue(ArraySortPipe) | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment