I have this array. I want to group by createdAt.
[
{
"createdAt": "2021-05-17T14:55:29.836Z",
"machine": {
"label": "MAQ_100",
},
},
{
"createdAt": "2021-03-10T13:22:45.694Z",
"machine": {
"label": "MAQ_33",
},
},
{
"createdAt": "2021-03-10T13:22:44.766Z",
"machine": {
"label": "MAQ_33",
},
},
{
"createdAt": "2019-04-13T10:06:13.120Z",
"machine": {
"label": "MAQ_33",
},
},
{
"createdAt": "2015-05-01T09:48:08.463Z",
"machine": {
"label": "MAQ_33",
},
},
{
"createdAt": "2015-05-01T09:48:08.463Z",
"machine": {
"label": "MAQ_77",
},
}
],
This is my expected result. I want the previous array grouped by createdAt and push each item if it has the same createdAt.
[
{"createdAtDates": ["17-05-2021"]},
{"createdAtDates: ["10-03-2021","10-03-2021"]},
{"createdAtDates": ["13-04-2019"]},
{"createdAtDates": ["01-05-2015","01-05-2015"]}
]
This is what I have done:
grouppedPallets() {
return this.items.reduce(function (pallets, pallet) {
const groups = pallets.filter((item) => item.date === pallet.date);
const found = groups.length === 1;
const group = found ? groups[0] : { createdAt: pallet.date, createdAtDates: [] };
group.createdAtDates.push(pallet.date);
if (!found) pallets.push(group);
return pallets;
}, []);
},
items() {
return this.palletsConnection
?
this.palletsConnection.values.map((pallet) => ({
...pallet,
date: formatDate(pallet.createdAt), //FORMAT DD-MM-YYYY
}))
: [];
},
This is what my grouppedPallet() does:
[
{
"createdAt": "17-05-2021",
"createdAtDates": ["17-05-2021"]
},
{
"createdAt": "10-03-2021",
"createdAtDates": ["10-03-2021","10-03-2021"]
},
{
"createdAt": "13-04-2019",
"createdAtDates": ["13-04-2019"]
},
{
"createdAt": "01-05-2015",
"createdAtDates":["01-05-2015","01-05-2015"]
}
]
I only want to store the createdAtDates after having reduced the array.