-1

I have an array of objects where an object can look like this:

{
    "id": "d630baff-0caf-4c9a-88a2-fc4c99fab2a4",
    "created": "2021-01-24 20:27:28",
    "last_updated": "2021-01-20 13:17:44"
}

I want to sort based on either value that is largest of created or last_updated. I'm able to perform this in SQL by querying ORDER BY GREATEST(created, last_updated) DESC, but how would I achieve this in Javascript? I have tried doing objs.sort((a, b) => (a.created > b.last_updated) ? 1 : -1) but it doesn't result in the right order.

Leomania
  • 13
  • 2
  • 1
    Try to parse does "created" and "last_updated" to Date object of javascript. https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Date – Joel Garcia Nuño Jan 28 '21 at 10:30
  • 2
    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) – Mohammad Jan 28 '21 at 10:31

1 Answers1

0

You could select the greater ISO 8601 date

const
    greatest = (a, b) => a >= b ? a : b,
    object = {
        id: "d630baff-0caf-4c9a-88a2-fc4c99fab2a4",
        created:      "2021-01-24 20:27:28",
        last_updated: "2021-01-20 13:17:44"
    }

console.log(greatest(object.created, object.last_updated));

and then sort by

array.sort((a, b) => greatest(a.created, a.last_updated)
    .localeCompare(greatest(b.created, b.last_updated)
)
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324