0

So consider the following image of an array of objects where its date: array

enter image description here

It's clear to see that this array is out of order, there are tons of examples of sorting an array of objects where there is a date key with a value of the date. But there seem to be no example wheres I can sort this array of objects where the key of the object is the date.

Ideas?

This answer is the closest answer I could find but again my date, as you can see if the key of the object.

Cœur
  • 34,719
  • 24
  • 185
  • 251
TheWebs
  • 11,302
  • 29
  • 90
  • 187

2 Answers2

1

Alternative to georg's way.

data = [
    {[new Date(2014, 1, 2)]: 1},
    {[new Date(2013, 2, 3)]: 1},
    {[new Date(2016, 3, 4)]: 1},
    {[new Date(2014, 4, 5)]: 1},
    {[new Date(2015, 1, 6)]: 1},
    {[new Date(2016, 2, 2)]: 1},
    {[new Date(2014, 3, 3)]: 1},
    {[new Date(2015, 4, 4)]: 1},
    {[new Date(2013, 5, 5)]: 1}
];

data.sort((a, b) =>
          Date.parse(Object.keys(a)[0]) -
          Date.parse(Object.keys(b)[0]))

console.log(data)
knutesten
  • 596
  • 3
  • 16
0

Consider:

data = [
    {[new Date(2014, 1, 2)]: 1},
    {[new Date(2013, 2, 3)]: 1},
    {[new Date(2016, 3, 4)]: 1},
    {[new Date(2014, 4, 5)]: 1},
    {[new Date(2015, 1, 6)]: 1},
    {[new Date(2016, 2, 2)]: 1},
    {[new Date(2014, 3, 3)]: 1},
    {[new Date(2015, 4, 4)]: 1},
    {[new Date(2013, 5, 5)]: 1}
];

result = data
    .map(obj => [Date.parse(Object.keys(obj)[0]), obj])
    .sort((x, y) => x[0] - y[0])
    .map(x => x[1]);


console.log(result);

This uses a technique called "decorate-sort-undecorate" oder Schwartzian transform.

georg
  • 204,715
  • 48
  • 286
  • 369