1

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

];

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.