0

I have a JSON file which contains the following data:

{
  "Aug 24, 2020": [
    "weather alert.",
    "new message",
    "you have a new request.",

  ],
  "Aug 23, 2020": [
    "weather alert.",
    "new message",
    "you have a new request.",
  ],
  "Aug 22, 2020": [
    "weather alert.",
    "new message",
    "you have a new request.",
  ]
}

I want to sort the key (dates) before using the JSON data in my code. Is it possible to sort date in this format in Javascript?

ninsonTan
  • 361
  • 1
  • 2
  • 17
  • https://stackoverflow.com/questions/4222690/sorting-a-json-object-in-javascript – zvi Aug 25 '20 at 20:24
  • Don't expect properties of an object to be sorted. Although there is some logic behind how they are ordered, the best practice is to us an *array* when order is important, not a plain object. – trincot Aug 25 '20 at 20:25
  • Are you really working with JSON here, or is this a JavaScript object (that doesn't need JSON parsing)? – trincot Aug 25 '20 at 20:29
  • Since ES6 keys are guaranteed to be in order of insertion. In ES5 they were not guaranteed by the standard to be in order. – Adrian Brand Aug 25 '20 at 20:43

2 Answers2

0

You can sort the properties by key as Date objects:

let dates = {
  "Aug 24, 2020": [
    "weather alert.",
    "new message",
    "you have a new request.",

  ],
  "Aug 23, 2020": [
    "weather alert.",
    "new message",
    "you have a new request.",
  ],
  "Aug 22, 2020": [
    "weather alert.",
    "new message",
    "you have a new request.",
  ]
}
dates = Object.keys(dates)
          .sort((a,b) => new Date(a) - new Date(b))
          .reduce(function (result, key) {
               result[key] = dates[key];
               return result;
          }, {});

console.log(dates);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
0

const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

const parseDate = str => new Date(
  parseInt(str.substr(8, 4)),
  months.indexOf(str.substr(0, 3)),
  parseInt(str.substr(4, 2))
);

const values = {
  "Aug 24, 2020": [
    "weather alert.",
    "new message",
    "you have a new request.",

  ],
  "Aug 23, 2020": [
    "weather alert.",
    "new message",
    "you have a new request.",
  ],
  "Aug 22, 2020": [
    "weather alert.",
    "new message",
    "you have a new request.",
  ]
};

const sortKeysByDate = obj => Object.keys(obj)
  .sort((a, b) => parseDate(a).getDate() - parseDate(b).getDate())
  .reduce((result, key) => {
    result[key] = obj[key];
    return result;
  }, {});

console.log(sortKeysByDate(values));
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60