I have an array of objects containing dates and I need to categorize them based on specific date categories.
const orders = [
{
"order_id": "1",
"description": "Description 1",
"date": "2024-02-03T19:00:57.744Z",
},
{
"order_id": "2",
"description": "Description 2",
"date": "2024-02-04T19:00:57.744Z",
},
{
"order_id": "3",
"description": "Description 3",
"date": "2024-02-06T19:00:57.744Z",
},
]
In addition, there are predefined date categories:
const category = [
'Overdue',
'Today',
'Tomorrow',
'This Week',
'Next Week',
'This Month',
'Next Month',
'Later',
'No Date',
];
The goal is to create a new array with sorted data based on the specified date categories.
Expected output:
[
{
"category": "Today",
"data": [
{
"order_id": "1",
"description": "Description 1",
"date": "2024-02-03T19:00:57.744Z"
}
]
},
{
"category": "Tomorrow",
"data": [
{
"order_id": "2",
"description": "Description 2",
"date": "2024-02-04T19:00:57.744Z"
}
]
},
{
"category": "This Week",
"data": [
{
"order_id": "3",
"description": "Description 3",
"date": "2024-02-06T19:00:57.744Z"
}
]
}
]
A custom function using dayjs library is used to determine the appropriate category for each date.
const getCategoryByDate = date => {
// Function logic goes here
};
To transform the original array into the desired format, Array.reduce
method is utilized.
const output = orders.reduce((acc, curr) => {
// Transformation logic goes here
}, []);
However, it's important to note that the output
array might not be in the correct order if the original orders
array is not pre-sorted by date.