import {Pipe, PipeTransform} from 'angular2/core';
@Pipe({ name: 'orderBy' })
export class OrderrByPipe implements PipeTransform {
transform(records: Array<any>, args?: any): any {
return records.sort(function(a, b){
if(a[args.property] < b[args.property]){
return -1 * args.direction;
}
else if( a[args.property] > b[args.property]){
return 1 * args.direction;
}
else{
return 0;
}
});
};
}
请检查一下,它对我有用,但我看到一件事,整数排序假设我们采取1,2,3,4,5,6,7,8,9,10,11,12, 13。这表现得很奇怪
答案 0 :(得分:0)
排序数组时遇到的一般问题是由于数组中使用的数据类型。
作为一个例子 -
console.log(2 > 11) //result is false
console.log("2" > "11") //result is true
这就是为什么你的管道对于从1到9的数字正常工作而在9之后失败的原因。
因此,应该考虑所比较项目的数据类型来处理数组元素的比较。
编辑 - 排序
请考虑以下示例,其中字符串和数字类型比较是分开处理的。
function orderByComparator(a, b) {
if ((isNaN(parseFloat(a)) || !isFinite(a)) || (isNaN(parseFloat(b)) || !isFinite(b))) {
//Isn't a number so lowercase the string to properly compare
if (a.toLowerCase() < b.toLowerCase())
return -1;
if (a.toLowerCase() > b.toLowerCase())
return 1;
}
else {
//Parse strings as numbers to compare properly
if (parseFloat(a) < parseFloat(b))
return -1;
if (parseFloat(a) > parseFloat(b))
return 1;
}
return 0; //equal each other
}
console.log("number comparison - ", orderByComparator(2, 11));
console.log("string comparison - ", orderByComparator("2", "11"));
&#13;
实施例
this plunkr详细解释了比较(检查orderBy.ts管道定义)
我希望这会有所帮助:)