0

I retrieve an array of objects and I need to format it to make it acceptable for Google Charts. The initial data looks like so

[
   {
      "itemOne":111,
      "itemTwo":1,
      "itemThree":"2022-02-01T00:00:00.000Z"
   },
   {
      "itemOne":222,
      "itemTwo":2,
      "itemThree":"2022-01-01T00:00:00.000Z"
   },
   {
      "itemOne":333,
      "itemTwo":3,
      "itemThree":"2021-12-01T00:00:00.000Z"
   },
]

To start the formatting, I do the following

const chartData = data.lastYear.map(
    (item) => ([item.itemThree, item.itemTwo, item.itemOne]),
);

Which now leaves me with this.

[
    ["2022-02-01T00:00:00.000Z", 1, 111],
    ["2022-01-01T00:00:00.000Z", 2, 222],
    ["2021-12-01T00:00:00.000Z", 3, 333],
]

I have been trying however to sort the above by date. My current attempt is pretty bad, and obviously doesnt work.

 const chartData = data.lastYear.map(
    (item) => ([item.itemThree, item.itemTwo, item.itemOne]),
  ).sort((a, b) => {
    return new Date(b.date) - new Date(a.date);
  });
  

So what would be the best way to sort everything by date?

Thanks

TTBox
  • 117
  • 1
  • 8

1 Answers1

2
let data = [
   {
      "itemOne":111,
      "itemTwo":1,
      "itemThree":"2022-02-01T00:00:00.000Z"
   },
   {
      "itemOne":222,
      "itemTwo":2,
      "itemThree":"2022-01-01T00:00:00.000Z"
   },
   {
      "itemOne":333,
      "itemTwo":3,
      "itemThree":"2021-12-01T00:00:00.000Z"
   },
]
data.sort((a,b)=>{
    return new Date(b.itemThree) - new Date(a.itemThree);
})

This sorts your data array according to date. Hope this is helpful

Hritik Sharma
  • 1,756
  • 7
  • 24
  • The sort function body can be simply `(a, b)=> a.itemThree - b.itemThree` regardless of whether the values to sort are strings or Date objects since the stringa are ISO 8601 compliant. This also sorts the original data, not the array produced by *map*. Sorting by date has been covered many, many times before. – RobG Feb 22 '22 at 22:46