Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Map and sort data by date

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
    ["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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading