Search code examples
javascriptmomentjsdayjs

Sort an array of objects containing a date array


I am currently attempting to sort an array of objects, and each object contains an array of dates. The data structure looks like the following:

const array = [
  {
    name: "Judith",
    cal: {
      ti: [
        "2021-03-09T15:00:00Z",
        "2021-03-09T15:30:00Z",
        "2021-03-16T14:00:00Z"
      ]
    }
  },
  {
    name: "billy",
    cal: {
      ti: [
        "2021-03-05T14:30:00Z",
        "2021-03-08T14:00:00Z",
        "2021-03-08T14:30:00Z"
      ]
    }
  }
]

I am attempting to sort the array based on the closest available time to now using the date library known as dayjs. I am attempting to compare each array of dates using the diff method within the dayjs package like so:

const test = array.map(i => i.cal.ti.sort((a, b) => {
 dayjs(a).diff(dayjs(b))
}))

console.log(test)

I would like to sort the objects contained within the array returning the object with the closest available time first and so on and so forth. I am noticing I am returning incorrectly within the sort and I believe I have a whole mess of issues going on as well, where I am not comparing the dates correctly causing my sort of the array to fail.

Attached is a repl.it for debugging:

https://repl.it/@rterrell25/LegalJaggedCoordinate#index.js


Solution

  • try this:

    const array = [
      {
        name: "Judith",
        cal: {
          ti: [
            "2021-03-16T14:00:00Z",
            "2021-03-09T15:00:00Z",
            "2021-03-09T15:30:00Z",
            "2021-03-19T15:30:00Z",
            "2021-02-19T15:30:00Z",
          ]
        }
      },
      {
        name: "billy",
        cal: {
          ti: [
            "2021-03-08T14:00:00Z",
            "2021-03-05T14:30:00Z",
            "2021-02-25T14:30:00Z",
            "2021-03-25T14:30:00Z",
            "2021-03-08T14:30:00Z"
          ]
        }
      }
    ];
    
    const now = new Date();
    
    array.forEach(i => i.cal.ti.sort((a, b) =>
        Math.abs(new Date(a) - now)
        - Math.abs(new Date(b) - now)
    ));
    
    array.sort((a, b) =>
        Math.abs(new Date(a.cal.ti[0]) - now)
        - Math.abs(new Date(b.cal.ti[0]) - now)
    );
    
    console.log(array);