简体   繁体   English

在两个条件下进行排序的对象数组

[英]Array of Objects with sorting on two conditions

I have an Array of Object. 我有一个对象数组。 I need to sort it using two conditions. 我需要使用两个条件对其进行排序。

[{
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
}, ]

I need to sort this using two conditions. 我需要使用两个条件对此进行排序。

  1. All the object with status 1 should come first 状态为1的所有对象应排在最前面
  2. The Date should be in descending order ie, Highest date first. 日期应按降序排列,即最高日期在前。

Here's the expected output 这是预期的输出

[{
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
}, ]

What i tried is followed this answer 我试过的是这个答案

Assigned the array to data and then 将数组分配给数据,然后

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

But it didn't sort using the start_date 但是它没有使用start_date进行排序

Here's my Fiddle 这是我的小提琴

You could use Array#sort and a sort function with a chained approach for the sort criteria. 您可以使用Array#sort和带有链接方法的排序函数作为排序条件。 You could use EPOCH time directly. 您可以直接使用EPOCH时间

It wotks with evaluating the first delta and check if the vakue us truthy, that neasb the value is either smaller than one or grater than one in this case. 它首先评估第一个增量,然后检查vakue us是否真实,以防在这种情况下该值小于1或大于1。 If the value is zero, then both status values are equal and the next delta for the time is evaluated. 如果该值为零,则两个状态值均相等,并评估该时间的下一个增量。 Then the result is returned. 然后返回结果。

  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; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM