Abdo Rabah
Abdo Rabah

Reputation: 2072

TypeError: undefined is not an object after Sorting an array?

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

Upvotes: 0

Views: 193

Answers (1)

andy mccullough
andy mccullough

Reputation: 9591

you'll need to use the optional chaining operator to allow for gracefully handling properties that don't exist on your objects -

a.orderInformation?.order?.order_date

and

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

console.log(res)

Upvotes: 2

Related Questions