我想按日期和计数对数组进行排序,我只能按日期对数组进行排序,数据如下所示
count date
"0" "2018-03-06T07:09:02+00:00"
"0" "2018-03-06T07:07:02+00:00"
"0" "2018-03-06T07:06:03+00:00"
"0" "2018-03-06T07:02:06+00:00"
"0" "2018-03-06T06:39:55+00:00"
"0" "2018-03-06T06:30:14+00:00"
"1" "2018-03-06T06:22:20+00:00"
"1" "2018-03-06T06:07:04+00:00"
"0" "2018-03-06T06:03:17+00:00"
"14" "2018-03-01T10:28:27.998000+00:00"
"0" null
"0" null
"0" null
我的代码在下面..
this.nodelist.sort((a, b) => {//lastDate dsc
if (new Date(b.lastDate) > new Date(a.lastDate)) {
return 1;
}
if (new Date(b.lastDate) < new Date(a.lastDate)) {
return -1;
}
return 0;
});
我想按计数和日期对数组进行排序,这意味着如果数组有计数&gt; 0然后它应该是第一个然后计数为零和最后所有其他记录。任何人都可以帮我解决这个问题吗?
答案 0 :(得分:4)
您可以使用您的代码并按照以下方式进行修改:
this.nodelist.sort((a, b) => {
// 1st property, sort by count
if (a.count > b.count)
return -1;
if (a.count < b.count)
return 1;
// 2nd property, sort by date
if (new Date(b.lastDate) > new Date(a.lastDate))
return 1;
if (new Date(b.lastDate) < new Date(a.lastDate))
return -1;
return 0;
});
它是如何运作的? 前两个if语句将按count对数组进行排序。 如果count相等,代码将考虑第二个属性(lastDate)。
答案 1 :(得分:1)
试试这个:
let xyz = numbers.sort(function(a, b) {
var countA = a.count;
var countB = b.count;
var dateA = new Date(a.date);
var dateB = new Date(b.date);
if(countA == countB)
{
return (dateB < dateA) ? -1 : (dateB > dateA) ? 1 : 0;
}
else
{
return (countB < countA) ? -1 : 1;
}
});
console.log(xyz);