Sort Array by timestamp of differently-structured objects

Viewed 19

I have an array of objects that adhere to 2 different structures. Simplified example below:

1.

{
  Foo: {
    "Bar": {
      "timestamp": "09/20/2022"
    }
  }
}
{
  Baz: {
    "Mok": {
      "timestamp": "09/22/2022"
    }
  }
}

I'm trying to sort the array by each object's timestamp in descending order. In my .sort() function I've tried first checking to see which structure the objects being compared adhere to and then comparing the timestamps, but I'm not having any luck - the objects remain in the same position within the array. The timestamps are in the provided format. Any help is appreciated, thanks!

1 Answers

Your big problem is that you don't necessarily know what format that timestamp is in. Usually a timestamp is just a string of numbers (the number of (milli)seconds since 1 Jan 1970) or it's an object that describes the formatting.

If you can reliably assume that your timestamp will always be in the American MM/DD/YYYY format, you can pass each section to the Date function and create a timestamp from that.

function formattedTime2Date(formatted) {

    const [
        month,
        day,
        year
    ] = formatted.split("/");

    return new Date(year, month - 1, day);

}

A Date object will automatically convert itself into a timestamp and you can check that in .sort()

// Sort from smallest to largest
timestamps.sort((a, b) => a - b);
Related