import { Injectable } from '@angular/core' ; @ Injectable ( ) export class Sorter { property : string = null ; direction : number = 1 ; sort ( collection , prop ) { this . property = prop ; this . direction = ( this . property === prop ) ? this . direction * - 1 : 1 ; collection . sort ( ( a , b ) => { let aVal ; let bVal ; if ( prop && prop . indexOf ( '.' ) ) { aVal = this . resolveProperty ( prop , a ) ; bVal = this . resolveProperty ( prop , b ) ; } else { aVal = a [ prop ] ; bVal = b [ prop ] ; } if ( this . isString ( aVal ) ) aVal = aVal . trim ( ) . toUpperCase ( ) ; if ( this . isString ( bVal ) ) bVal = bVal . trim ( ) . toUpperCase ( ) ; if ( aVal === bVal ) { return 0 ; } else if ( aVal > bVal ) { return this . direction * - 1 ; } else { return this . direction * 1 ; } } ) ; } isString ( val ) { return ( val && ( typeof val === 'string' || val instanceof String ) ) ; } resolveProperty ( path , obj ) { return path . split ( '.' ) . reduce ( function ( prev , curr ) { return ( prev ? prev [ curr ] : undefined ) ; } , obj || self ) ; } }