Home > database >  Map and sort data by date
Map and sort data by date

Time:02-23

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

CodePudding user response:

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

  • Related