SA__
SA__

Reputation: 437

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
  2. The Date should be in descending order i.e., 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

Here's my Fiddle

Upvotes: 0

Views: 63

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386883

You could use Array#sort and a sort function with a chained approach for the sort criteria. You could use EPOCH time directly.

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

Upvotes: 3

Related Questions