M Has Khan
M Has Khan

Reputation: 23

How to sort an array of object with two dates?

My array:

var arr = [
  {id: 1, start_date:'2020-04-13', end_date: '2020-07-05'},
  {id: 2, start_date:'2020-04-13', end_date: '2020-07-16'},
  {id: 3, start_date:'2020-05-25', end_date: '2020-12-31'},
  {id: 4, start_date:'2020-07-01', end_date: '2020-12-31'},
  {id: 5, start_date:'2020-07-01', end_date: '2020-08-02'}
];

I want to sort this array according to the start_date and end_date. The way it should work is that start_date is to be arranged in descending order, i.e. The later the date, the higher it is placed in the array. However, if there are multiple start_dates containing the same date then it should look at the end_date. In this scenario, end_date should be arranged in the ascending order.

I am trying to get the array in this format:

var new_arr = [
  {id: 5, start_date:'2020-07-01', end_date: '2020-08-02'},
  {id: 4, start_date:'2020-07-01', end_date: '2020-12-31'},
  {id: 3, start_date:'2020-05-25', end_date: '2020-12-31'},
  {id: 1, start_date:'2020-04-13', end_date: '2020-07-05'},
  {id: 2, start_date:'2020-04-13', end_date: '2020-07-16'}

];

Upvotes: 1

Views: 397

Answers (1)

Derek Wang
Derek Wang

Reputation: 10204

You can implement it using Array.sort method.

var arr = [
  {id: 1, start_date:'2020-04-13', end_date: '2020-07-05'},
  {id: 2, start_date:'2020-04-13', end_date: '2020-07-16'},
  {id: 3, start_date:'2020-05-25', end_date: '2020-12-31'},
  {id: 4, start_date:'2020-07-01', end_date: '2020-12-31'},
  {id: 5, start_date:'2020-07-01', end_date: '2020-08-02'}
];

var result = arr.sort((a, b) => {
  if (a.start_date < b.start_date) {
    return 1;
  } else if (a.start_date === b.start_date) {
    if (a.end_date > b.end_date) {
      return 1;
    } else {
      return 0;
    }
  } else {
    return 0;
  }
});

console.log(result);

Upvotes: 2

Related Questions