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:
[[
{
"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"
},
]]
CodePudding user response:
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);
CodePudding user response:
the second example is actually invalid JSON. a better structure if you want these grouped by date, may be to put them into an object, with date as the key for each array of objects. try this:
const inputData = [
{
"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 outputData = {};
inputData.forEach( item => {
const date = item.courierDate.slice( 0, 10 );
if ( !outputData.hasOwnProperty( date ) ) outputData[date] = [];
outputData[date].push( item );
} );
console.log( outputData );
CodePudding user response:
Build an object with keys as "Date" and values are aggregated for the same date. Use Object.values
to get expected output.
const merge = (arr) => {
const track = {};
arr.forEach((item) => {
const date = new Date(item.courierDate).toLocaleDateString();
if (!track[date]) {
track[date] = [];
}
track[date].push(item);
});
return Object.values(track);
};
const data = [
{
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",
},
];
console.log(merge(data));