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'}];
Abdo Rabah
  • 1,670
  • 2
  • 15
  • 31
  • 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? – DBS Jul 12 '21 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? – Nir Alfasi Jul 12 '21 at 13:59
  • https://stackoverflow.com/questions/5002848/how-to-define-custom-sort-function-in-javascript, https://stackoverflow.com/q/1129216/1427878 – CBroe Jul 12 '21 at 13:59
  • Does this answer your question? [How to sort an object array by date property?](https://stackoverflow.com/questions/10123953/how-to-sort-an-object-array-by-date-property) – Kinglish Jul 12 '21 at 14:00

2 Answers2

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);
Spectric
  • 30,714
  • 6
  • 20
  • 43
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);