角管分选 [英] Angular pipe sorting
问题描述
根据此问题-> 按角度4的升序和降序
我制作了相同的管道,但是它不能自然地对数字进行排序.我的意思是2是>然后是11.
I've made the same pipe, but it can't sort numbers naturally. I mean 2 is > then 11.
如何修改此管道以同时对字符串和数字进行排序?
How can this pipe be modified to sort both string and numbers?
@Pipe({
name: 'orderBy'
})
export class OrderByPipe implements PipeTransform {
transform(records: Array<any>, args?: any): any {
if (records && records.length > 0) {
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;
}
});
}
}
}
推荐答案
这是因为您将这些值按字符串的形式(按字典顺序)排序.管道的输入似乎是Array<{ [propertyName: string]: [value: string] }>
类型.
That's because you are sorting the values as strings - lexicographically. The input for your pipe seems to be of type Array<{ [propertyName: string]: [value: string] }>
.
在比较之前,请确保输入属性值是数字或将值转换为number
.
Either make sure that the input property values are numbers or convert the values to number
before comparing.
如果您需要根据管道中数据的类型进行排序,则可以使用以下内容:
In case you need to sort based on the type of the data that came to your pipe, you can use something like this:
@Pipe({
name: 'orderBy'
})
export class OrderByPipe implements PipeTransform {
transform(records: Array<any>, args?: any): any {
if (records && records.length > 0) {
return records.sort(
(a, b) => args.direction * (
typeof a[args.property] === 'number'
? (a[args.property] - b[args.property])
: a[args.property] > b[args.property] ? 1 : -1)
);
}
}
}
希望这会有所帮助:-)
Hope this helps a little :-)
这篇关于角管分选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!