请帮我排序数组(数组应根据sdate以及edate和sdate的差异进行排序)
输入数组对象: -
[{sdate:'03/20/2017',edate:'03/21/2017',id:1},
{sdate:'03/20/2017',edate:'03/24/2017',id:2},
{sdate:'03/20/2017',edate:'03/20/2017',id:3},
{sdate:'03/19/2017',edate:'03/20/2017',id:4}]
输出数组对象: -
[{sdate:'03/19/2017',edate:'03/20/2017',id:4},
{sdate:'03/20/2017',edate:'03/24/2017',id:2},
{sdate:'03/20/2017',edate:'03/21/2017',id:1},
{sdate:'03/20/2017',edate:'03/20/2017',id:3}]
我尝试过:
arrObj.sort(function(a,b){
return new Date(a.sdate) - new Date(b.sdate);
});
它只返回基于sdate
的排序数组,但如果sdate
相同,那么对象应首先出现,其中天数差异较大(edate -sdate)
答案 0 :(得分:2)
这应该做的伎俩:) 这里按edate(反向)排序,如果sdates相同..
Arr = [{sdate:'03/20/2017',edate:'03/21/2017',id:1},
{sdate:'03/20/2017',edate:'03/24/2017',id:2},
{sdate:'03/20/2017',edate:'03/20/2017',id:3},
{sdate:'03/19/2017',edate:'03/20/2017',id:4}];
Arr.sort(function(a, b) {
if(a.sdate === b.sdate){
return new Date(b.edate) - new Date(a.edate);
}
return new Date(a.sdate) - new Date(b.sdate);
});
console.log(Arr);

答案 1 :(得分:0)
我的两分钱:
[{
sdate: '03/20/2017',
edate: '03/21/2017',
id: 1
}, {
sdate: '03/20/2017',
edate: '03/24/2017',
id: 2
}, {
sdate: '03/20/2017',
edate: '03/20/2017',
id: 3
}, {
sdate: '03/19/2017',
edate: '03/20/2017',
id: 4
}].sort(function(a, b) {
var sdateA = +new Date(a.sdate)
, sdateB = +new Date(b.sdate)
, edateA = +new Date(a.edate)
, edateB = +new Date(b.edate);
return sdateA === sdateB ? edateB - edateA : sdateA - sdateB;
})