0

I'd like to sort this JavaScript array by three values, but I can't seem to figure out how to sort by more than one property at a time.

The requirements are:

  1. by createdAt in descending order
  2. by status in descending order
  3. by end in ascending order

This is the array:

var items [
    { status: 3, end: 2020-06-19, createdAt: 2020-06-23T07:14:59.591Z},
    { status: 2, end: 2020-06-19, createdAt: 2020-06-21T07:14:59.591Z},
    { status: 1, end: 2020-06-01, createdAt: 2020-06-23T07:14:59.591Z},
    { status: 3, end: 2020-06-05, createdAt: 2020-06-22T07:14:59.591Z},
    { status: 3, end: 2020-06-02, createdAt: 2020-06-22T07:14:59.591Z},
];

The result should be:

var items [
    { status: 3, end: 2020-06-19, createdAt: 2020-06-23T07:14:59.591Z},
    { status: 1, end: 2020-06-01, createdAt: 2020-06-23T07:14:59.591Z},
    { status: 3, end: 2020-06-02, createdAt: 2020-06-22T07:14:59.591Z},
    { status: 3, end: 2020-06-05, createdAt: 2020-06-22T07:14:59.591Z},
    { status: 2, end: 2020-06-19, createdAt: 2020-06-21T07:14:59.591Z},
];

I tried.

test.sort((a, b) => 
      new Date(b[type].createdAt) - new Date(a[type].createdAt) 
      || b[type].status - a[type].status 
      || Date.parse(a[type].end) - Date.parse(a[type].end));

It failed.....

tigerJK
  • 35
  • 9

1 Answers1

0

You can put OR condition for multiple sort condition:

items.sort((a,b)=>{
    return new Date(b.createdAt)-new Date(a.createdAt) || b.status-a.status || new Date(a.end)-new Date(b.end)
})
gorak
  • 5,233
  • 1
  • 7
  • 19