[英]How to sort array of object by key?
I tried this method: 我尝试了这种方法:
if (field == 'age') {
if (this.sortedAge) {
this.fltUsers.sort(function (a, b) {
if (b.totalHours > a.totalHours) {
return 1;
}
});
this.sortedAge = false;
} else {
this.sortedAge = true;
this.fltUsers.sort(function (a, b) {
if (b.totalHours < a.totalHours) {
return 1;
}
});
}
}
So I have array of objects. 所以我有对象数组。 Each object has property:
totalHours
. 每个对象都有属性:
totalHours
。
I need to order this array by desc/asc this field totalHours
after click. 单击后,我需要通过desc / asc对该字段进行
totalHours
,此字段totalHours
。
My code does not work. 我的代码不起作用。
I usually follow 1-line rule for the kind of simple comparator like yours, so I would modify it like this 对于像您这样的简单比较器,我通常遵循1行规则,因此我会像这样修改它
this.fltUsers.sort((a,b) => b.totalHours < a.totalHours ? 1 : -1);
You need at least 1
and -1
returned so that the comparator logic can work. 您至少需要返回
1
和-1
才能使比较器逻辑正常工作。
This code must sort the array. 此代码必须对数组进行排序。
function compare(a,b) {
if (b.totalHours < a.totalHours)
return -1;
if (b.totalHours > a.totalHours)
return 1;
return 0;
}
objects.sort(compare);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.