I am trying to sort an array of strings by numerical value in Angular2 using a custom pipe (I did not write this pipe). Here is the pipe:
import { Pipe, PipeTransform } from "@angular/core";
@Pipe( { name: 'numericalSort' } )
export class NumericalSortPipe implements PipeTransform {
transform( array: Array<any>, orderField: string, orderType: boolean ): Array<string> {
array.sort( ( a: any, b: any ) => {
let ae = a[ orderField ];
let be = b[ orderField ];
if ( ae == undefined && be == undefined ) return 0;
if ( ae == undefined && be != undefined ) return orderType ? 1 : -1;
if ( ae != undefined && be == undefined ) return orderType ? -1 : 1;
if ( ae == be ) return 0;
return orderType ? (ae.toString().toLowerCase() > be.toString().toLowerCase() ? -1 : 1) : (be.toString().toLowerCase() > ae.toString().toLowerCase() ? -1 : 1);
} );
return array;
}
}
Here is the object. I need to be able to sort numerically by "label".
{
"id" : "12345678",
"accountId" : "123456789",
"label" : "906",
"fullAddress" : {
"zip" : "12345"
}
}
Here is sample HTML:
<div *ngFor="let place of places | numericalSort: 'label'">
<h3>
{{place.label}}
</h3>
...
</div>
I am able to sort by the default alphabetical values. How can I sort by numerical value?
I'd add a new parameter to the pipe that will indicate the real type of a field. So, the pipe will be able to cast string fields of items in your array to real types:
And usage:
See the plunk.