Hey, I'm facing an issue while trying to organize an array of objects by grouping them based on Month and Year. Although I have managed to transform the data and extract the necessary months and years, not all items are being correctly placed within their respective groups.
Below is my code snippet:
const data = [
{text:"Lorem 1 ipsum", date:"Thu Feb 21 2019 11:44:24 GMT+0000 (GMT)"},
{text:"Lorem 2 ipsum", date:"Thu Feb 21 2019 11:44:24 GMT+0000 (GMT)"},
{text:"Lorem 3 ipsum", date:"Thu Mar 21 2019 11:44:24 GMT+0000 (GMT)"},
]
const texts = [];
const formattedData = data.reduce((acc, { date, text }) => {
const dateObj = new Date(date);
const monthYearFormat = dateObj
.toLocaleString("en-us", { month: "long", year: 'numeric' });
if(acc[monthYearFormat]) {
texts.push(text);
acc[monthYearFormat] = {
text: texts
}
} else {
acc[monthYearFormat] = {
text: [text]
}
}
return acc;
}, {})
console.log(formattedData)
The resulting output from this logic is:
{
February 2019: {
text: ['Lorem 2 ipsum']
},
March 2019: {
text: ['Lorem 3 ipsum']
}
}
It appears that my initial object is being replaced in the process. For instance, the group for February should also include "Lorem 1 ipsum" like so:
{
February 2019: {
text: ['Lorem 1 ipsum', 'Lorem 2 ipsum']
},
March 2019: {
text: ['Lorem 3 ipsum']
}
}
If you have any insights on where I might be going wrong, your help would be greatly appreciated. Thanks!