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

is there any way to group the object into multiple objects based on date in javascript

Here i am trying to group the object in multiple object based on date in javascript using map method but i am stuck in it, let me know if there is any solution of it.

   {orderData?.map((key,value)=>{
            <Card title={key?.courierDate} style={{ background: '#ffd0d7' }}>
                   <Card type="inner" style={{ background: '#ffe9ec' }}>
                                   {key?.courierStatus}
                   </Card> 
            </Card>                              
   }) }

Actual Object look like this:

[
        {
            "courierStatus": "Ready for Pick Up",
            "courierDate": "2022-07-30T11:50:28.758Z",
        },
        {
            "courierStatus": "Out for Delivery",
            "courierDate": "2022-07-30T18:33:01.775Z",
        },
        {
            "courierStatus": "Delivered",
            "courierDate": "2022-08-01T04:25:56.581Z",s"
        },
    ]

Expected Result:

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

 [[
    {
        "courierStatus": "Ready for Pick Up",
        "courierDate": "2022-07-30T11:50:28.758Z",
    },
    {
        "courierStatus": "Out for Delivery",
        "courierDate": "2022-07-30T18:33:01.775Z",
    },
  ],
  [
    {
        "courierStatus": "Delivered",
        "courierDate": "2022-08-01T04:25:56.581Z",s"
    },
  ]]

>Solution :

Naive solution.
Note the date format it doesn’t include leading zeros.

const arr = [
    {
        "courierStatus": "Ready for Pick Up",
        "courierDate": "2022-07-30T11:50:28.758Z"
    },
    {
        "courierStatus": "Out for Delivery",
        "courierDate": "2022-07-30T18:33:01.775Z"
    },
    {
        "courierStatus": "Delivered",
        "courierDate": "2022-08-01T04:25:56.581Z"
    }
];

const rarr = arr.reduce((acc, e) => {   
    const date = new Date(e.courierDate);
    const yyyy = date.getFullYear();
    const mm = date.getMonth() + 1;
    const dd = date.getDate();
    const key = `${dd}-${mm}-${yyyy}`;

    acc[key] ? acc[key].push(e) : acc[key] = [e];

     return acc; 
}, {})

console.log(rarr);
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