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 problem is i have order_date is inside another object and when i try to sort i'm having this error message
TypeError: undefined is not an object b.orderInformation.order.order_date`
const array = [
{ type : 'type1', created_at: '2021-07-31' },
{
type : 'type2',
orderInformation: { order: { order_date: '2021-07-13' } }
},
{
type : 'type2',
orderInformation: { order: { 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.orderInformation.order.order_date ?? b.created_at ?? b.updated_at) - new Date(a.orderInformation.order.order_date ?? a.created_at ?? a.updated_at);
})