0

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

3
  • 1
    orderInformation is undefined in the first element of the array (it doesn't exists) Commented Jul 16, 2021 at 13:45
  • @Ariel i know.. i said the array contains different objects Commented Jul 16, 2021 at 13:49
  • 2
    Yes, that's why you are getting the error. you'll need to check if the object has the property you are expecting Commented Jul 16, 2021 at 13:50

1 Answer 1

2

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)

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

2 Comments

But is this really a question and/or answer that will help future readers? Check the existence before you use it?
@Andreas, no need on created_at and updated_at, they are strings, not objects

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.