我想通過數值在Angular2中使用自定義管道對字符串數組進行排序(我沒有寫這個管道)。這是管道:Angular2數字orderBy管道
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;
}
}
這是對象。我需要能夠通過「標籤」進行數字排序。
{
"id" : "12345678",
"accountId" : "123456789",
"label" : "906",
"fullAddress" : {
"zip" : "12345"
}
}
下面是示例HTML:
<div *ngFor="let place of places | numericalSort: 'label'">
<h3>
{{place.label}}
</h3>
...
</div>
我能夠通過默認值按字母順序進行排序。我怎樣才能按數值排序?
如果您可以提供樣本輸入數組,orderfield和ordertype –
是否會很棒您的數組是否有字母數字,並且您希望訂購數字和字母? – Vega
我已經使用示例對象和HTML更新了帖子。 – bk819284