Skip to content

Instantly share code, notes, and snippets.

@nmai
Created January 23, 2016 11:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmai/087d213655ecd3bb292d to your computer and use it in GitHub Desktop.
Save nmai/087d213655ecd3bb292d to your computer and use it in GitHub Desktop.
Transforms arrays with ordering by date
/* 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