1

I have an array with different objects and they have different date fields that i want to sort regardless of the property name created_at, order_date or updated_at. How can i sort the array by the nearest date to today's date ?

The array looks like this :

const array = [{type : 'type1', created_at: '2021-07-31'}, {type : 'type2', order_date: '2021-07-13'}, {type : 'type2', order_date: '2021-07-07'}, {type : 'type1', created_at: '2021-08-05'}, {type : 'type3', updated_at: '2021-09-05'}];

4
  • 1
    To be clear, each object will only have a single date (either created_at OR order_date) and you want to sort by that date value regardless of the property name? Commented Jul 12, 2021 at 13:59
  • The question is not clear: these are two different fields: how should the sorting be done? by comparing first one of them then by the other? what if one of the fields is missing? Commented Jul 12, 2021 at 13:59
  • stackoverflow.com/questions/5002848/…, stackoverflow.com/q/1129216/1427878 Commented Jul 12, 2021 at 13:59
  • Does this answer your question? How to sort an object array by date property? Commented Jul 12, 2021 at 14:00

2 Answers 2

3

You can make use of Array.prototype.sort():

const array = [{
  type: 'type1',
  created_at: '2021-07-31'
}, {
  type: 'type2',
  order_date: '2021-07-13'
}, {
  type: 'type2',
  order_date: '2021-07-07'
}, {
  type: 'type1',
  created_at: '2021-08-05'
}, {
  type: 'type3',
  updated_at: '2021-09-05'
}];

const res = array.sort(function(a, b) {
  return new Date(b.created_at ?? b.order_date ?? b.updated_at) - new Date(a.created_at ?? a.order_date ?? a.updated_at);
})

console.log(res);

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

2 Comments

c = a.created_at ?? a.order_date also possible as d = b.created_at ?? b.order_date. Or using || for more compatibility
I have also another property in the array updated_at
3

You can try this

const array = [{type : 'type1', created_at: '2021-07-31'}, {type : 'type2', order_date: '2021-07-13'}, {type : 'type2', order_date: '2021-07-07'}, {type : 'type1', created_at: '2021-08-05'}, {type : 'type3', updated_at: '2021-09-05'}];

const sortedArray = array.sort(function(a,b){
  return new Date(b.order_date || b.created_at || b.updated_at) - new Date(a.order_date || a.created_at || a.updated_at);
});

console.log(sortedArray);

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.