0

I want to sort object by date.
This is object structure:

const dates = {
  3/1/20: 1,
  3/10/20: 31,
  3/11/20: 35,
  3/12/20: 60,
  3/13/20: 64,
  3/14/20: 70,
  3/15/20: 93,
  3/16/20: 112,
  3/17/20: 112,
  3/2/20: 14,
  3/3/20: 14,
  3/4/20: 16,
  3/5/20: 25,
  3/6/20: 26,
  3/7/20: 29,
  3/8/20: 30,
  3/9/20: 30
}

The problem is when date starts with number 1 it's listed like: 1, then 11, 12, 13, etc.
I want to be it sorted normaly: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, etc.

The object result I need is:

const dates = {
  3/1/20: 1,
  3/2/20: 14,
  3/3/20: 14,
  3/4/20: 16,
  3/5/20: 25,
  3/6/20: 26,
  3/7/20: 29,
  3/8/20: 30,
  3/9/20: 30,
  3/10/20: 31,
  3/11/20: 35,
  3/12/20: 60,
  3/13/20: 64,
  3/14/20: 70,
  3/15/20: 93,
  3/16/20: 112,
  3/17/20: 112
}

I have looked at this example, but they are using moment.js which I don't use/don't want to use.
Also I have looked at some answers on this post but this doesn't help me either.

zrna
  • 565
  • 1
  • 8
  • 20
  • 3
    your object structure is not a valid js – qiAlex Mar 18 '20 at 13:02
  • 1
    Use `console.log(JSON.stringify(dates, null, 2))` and copy and paste the result here instead of what you have there. You should consider using a different date format for your keys, like yyyy-MM-dd. – Heretic Monkey Mar 18 '20 at 13:05
  • did you notice that your object is not made to be sorted since its elements are only accessed using their key and that this type of object cannot offer access by iteration (except using an external method) ? – Mister Jojo Mar 18 '20 at 13:07

1 Answers1

2

Even though this can be achieved in some browsers.

There is no guarantee that the Object will be sorted in a specific order.

Arrays, on the other hand, can be sorted. A solution to this issue can be using an array of objects instead.

let dates = [
        {date: "3/1/20", value : 14},
        {date: "3/1/20", value : 14}
        .....
];

dates = dates.sort((a,b)=> new Date(b.date) - new Date(a.date));
Adi Darachi
  • 2,137
  • 1
  • 16
  • 29
  • 2
    Note that the Date constructor is not guaranteed to work correctly here: those aren't valid ISO 8601 date strings, which is why hereticmonkey suggested yyyy-mm-dd in the comments. Also note that any ES2015-compliant browser (basically, everything but IE) will retain insertion order for objects per the spec. – Jared Smith Mar 18 '20 at 13:14
  • This is not a [valid date format](https://stackoverflow.com/questions/51715259/what-are-valid-date-time-strings-in-javascript) and might break in some browsers. – str Mar 20 '20 at 10:25
  • 1
    @JaredSmith Insertion order only has to be retained [for *certain* operations](https://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties). – str Mar 20 '20 at 10:26