I have an array that I need to group by the createdAt
value.
[
{
"createdAt": "2021-05-17T14:55:29.836Z",
"machine": {
"label": "MAQ_100",
},
},
{
"createdAt": "2021-03-10T13:22:45.694Z",
"machine": {
"label": "MAQ_33",
},
},
...
],
The desired output should be having the elements grouped based on their createdAt values.
[
{"createdAtDates": ["17-05-2021"]},
{"createdAtDates": ["10-03-2021","10-03-2021"]},
...
]
To achieve this, here is the logic implemented:
grouppedItems() {
return this.items.reduce(function (groupedItems, item) {
const groups = groupedItems.filter((el) => el.createdAt === item.createdAt);
const found = groups.length === 1;
const group = found ? groups[0] : { createdAt: item.createdAt, createdAtDates: [] };
group.createdAtDates.push(item.createdAt);
if (!found) groupedItems.push(group);
return groupedItems;
}, []);
},
items() {
return this.connection
?
this.connection.values.map((item) => ({
...item,
createdAt: formatDate(item.createdAt), //FORMAT DD-MM-YYYY
}))
: [];
},
This function will result in the following structure:
[
{
"createdAt": "17-05-2021",
"createdAtDates": ["17-05-2021"]
},
...
]
The goal is to store only the formatted dates after reducing the initial array.