2017-03-04 47 views
0

我有一个对象数组。我需要使用两个条件进行分类。在两个条件下排序的对象数组

[{ 
id: 412, 
start_date: 1488479400, 
status: 1 
}, { 
id: 560, 
start_date: 1499451100, 
status: 0 
}, { 
id: 112, 
start_date: 1499091200, 
status: 0 
}, { 
id: 512, 
start_date: 1488474500, 
status: 1 
}, { 
id: 750, 
start_date: 1483473100, 
status: 1 
}, { 
id: 123, 
start_date: 1499106600, 
status: 0 
}, ] 

我需要使用两个条件对此进行排序。

  1. 所有与状态1的对象应该先
  2. 日期应该是在第一降序排列,即最高的日期。

这里的预期输出

[{ 
id: 750, 
start_date: 1483473100, 
status: 1 
}, { 
id: 512, 
start_date: 1488474500, 
status: 1 
}, { 
id: 412, 
start_date: 1488479400, 
status: 1 
}, { 
id: 112, 
start_date: 1499091200, 
status: 0 
}, { 
id: 123, 
start_date: 1499106600, 
status: 0 
}, { 
id: 560, 
start_date: 1499451100, 
status: 0 
}, ] 

我试过之后this answer

数组分配给数据,然后

data.sort(function(a,b){return a.start_date - b.start_date()});

但它没有那种使用start_date

Here's my Fiddle

+0

'b.start_date()'这不是一个功能。 –

+1

在你的小提琴中日期的格式不一样(事实上,在你的小提琴中它可能没有做你期望的,因为'01-01-2017' *没有*引号是数字-2017(1减1减2017) 。你的真实数据是否有你的问题中显示的'start_date'? – nnnnnn

回答

3

您可以使用Array#sort以及排序函数,并使用链接方式作为排序标准。您可以直接使用EPOCH time

它与评估第一个三角洲并检查是否使我们truthy,这neasb的价值要么小于一个或大于一在这种情况下。如果该值为零,则两个状态值相等,并评估该时间的下一个增量。然后返回结果。

delta  delta 
status start_date comment 
------ ---------- -------------------------- 
< 0     sort by status only to top 
    0  evaluate  sort by start_date as well 
> 0     sort by status only to bottom 

var array = [{ id: 412, start_date: 1488479400, status: 1 }, { id: 560, start_date: 1499451100, status: 0 }, { id: 112, start_date: 1499091200, status: 0 }, { id: 512, start_date: 1488474500, status: 1 }, { id: 750, start_date: 1483473100, status: 1 }, { id: 123, start_date: 1499106600, status: 0 }]; 
 

 
array.sort(function (a, b) { 
 
    return b.status - a.status || b.start_date - a.start_date; 
 
}); 
 

 
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+0

很好的使用'||' - 我以前没有想过在sort函数中这样做,我认为你已经得到了主要的排序(我怀疑OP还需要更多的解释,以了解它是如何工作的) – nnnnnn

+0

仅供参考:'status:1'似乎是代码中的最后一个,OP要求他们先来 – haxxxton

+0

@haxxxton You可以简单地反转表达式,使状态1首先出现:b.status - a.status – ifadey