Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort a JSON by Date?

I'm trying to loop through a JSON and sort it by the date so I can see the latest date to the oldest date, and then write it to the file.

Here is my code

var reader = JSON.parse(fs.readFileSync('txt.json', 'utf8'));
function sortByDate(a, b) {
    return new Date(a.lastUpdated).toJSON() - new Date(b.lastUpdated).toJSON();
}

reader.sort(sortByDate)

JSON Data Example

{
    "Data": {
        "Contents": [
            {
                "Key": [
                    "HelloTest"
                ],
                "lastUpdated": [
                    "2019-10-25T10:30:50.558Z"
                ]
            },
            {
                "Key": [
                    "TestHello"
                ],
                "lastUpdated": [
                    "2019-03-26T10:30:50.558Z"
                ]
            }
        ]
    }
}


like image 531
Cameron Shearer Avatar asked Mar 02 '26 05:03

Cameron Shearer


1 Answers

Here are a couple of errors I found in your code:

  • Your function name has a typo, it should be sortByDate and not sortbyDate.
  • You need top sort the inner json.Data.Contents array, not the outer json object.
  • You need to reference the first element of your lastUpdated arrays using lastUpdated[0].
  • Finally, you do not need to call toJSON() on the date objects in your sorting function, simply convert to date and return the difference.

Also your inner data fields are arrays, which seems strange for a Key and a lastUpdated value.

If you keep your fields as arrays, here is a working example showing how to sort the inner Data.Contents array by date:

const jsonString = `{
  "Data": {
    "Contents": [{
        "Key": ["HelloTest"],
        "lastUpdated": ["2019-10-25T10:30:50.558Z"]
      }, {
        "Key": ["TestHello"],
        "lastUpdated": ["2019-03-26T10:30:50.558Z"]
      }]
  }
}`;

function sortByDate(a, b) {
    return new Date(a.lastUpdated[0]) - new Date(b.lastUpdated[0]);
}

const json = JSON.parse(jsonString);
const defaultValue = { Data: { Contents: [] } };
const sortedContents = [...(json || defaultValue).Data.Contents].sort(sortByDate);
const output = { ...json, Data: { Contents: sortedContents } };

console.log(output);

If you change your fields to scalars, which I suggest, here is another example:

const jsonString = `{
  "Data": {
    "Contents": [{
        "Key": "HelloTest",
        "lastUpdated": "2019-10-25T10:30:50.558Z"
      }, {
        "Key": "TestHello",
        "lastUpdated": "2019-03-26T10:30:50.558Z"
      }]
  }
}`;

function sortByDate(a, b) {
    return new Date(a.lastUpdated) - new Date(b.lastUpdated);
}

const json = JSON.parse(jsonString);
const defaultValue = { Data: { Contents: [] } };
const sortedContents = [...(json || defaultValue).Data.Contents].sort(sortByDate);
const output = { ...json, Data: { Contents: sortedContents } };

console.log(output);
like image 65
jo_va Avatar answered Mar 03 '26 19:03

jo_va



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!