Search code examples
javascriptreactjsarrayssortingjavascript-objects

How can I sort an array full of objects by the date (which is represented by index 0-23 in the key attribute of each element)?


The following array is copied from the console and should demonstrate the structure of the array. It is an array with multiple objects, which all have a unique key: each key is a combination of a date and a unique identifier.

My question is, how can I sort the array so that I have all the objects sorted by the date (which is represented by index 0-23 in the key of each element)?

(5) [{…}, {…}, {…}, {…}, {…}]

0: {$$typeof: Symbol(react.element), type: 'div', key: '2023-01-22T04:00:00.000Z63c4a2b248f0a56684d4ffcd',
ref: null, props: {…}, …}
1: {$$typeof: Symbol(react.element), type: 'div', key: '2023-01-21T06:56:00.000Z63cb70559d1aa33902535ba2', ref: null, props: {…}, …}
2: {$$typeof: Symbol(react.element), type: 'div', key: '2023-01-30T18:00:00.000Z63cc668315bcc1b222020168', ref: null, props: {…}, …}
3: {$$typeof: Symbol(react.element), type: 'div', key: '2023-01-28T20:00:00.000Z63cc6c2415bcc1b2220201c6', ref: null, props: {…}, …}
4: {$$typeof: Symbol(react.element), type: 'div', key: '2023-01-27T19:00:00.000Z63cc6c5515bcc1b222020228', ref: null, props: {…}, …}

length: 5
[[Prototype]]: Array(0)


Solution

  • In this format, you can probably just sort comparing dates as strings (i.e. lexicographically). Something as simple as this could be fine. The rest of the string (i.e. the guid after the date) will be irrelevant because the order is determined by the first leading part:

    data.sort((a, b) => a.key < b.key ? -1 : 1)