I have an array of objects.
[
{ _id: { year: 2020, month: 1 } },
{ _id: { year: 2019, month: 1 } },
{ _id: { year: 2019, month: 2 } },
{ _id: { year: 2019, month: 4 } },
{ _id: { year: 2019, month: 5 } },
{ _id: { year: 2019, month: 8 } },
{ _id: { year: 2019, month: 9 } },
{ _id: { year: 2019, month: 11 } }
]
I want to remove the duplicate year properties from the objects and push different month data in one array object.
I want to get below output:
[
{
"_id": {
"year": 2020,
"month": [1]
}
},
{
"_id": {
"year": 2019,
"month": [1, 2, 4, 5, 8, 9, 11]
}
}
]
I have tried but cannot get the expected output:
let arr = [
{ _id: { year: 2020, month: 1 } },
{ _id: { year: 2019, month: 1 } },
{ _id: { year: 2019, month: 2 } },
{ _id: { year: 2019, month: 4 } },
{ _id: { year: 2019, month: 5 } },
{ _id: { year: 2019, month: 8 } },
{ _id: { year: 2019, month: 9 } },
{ _id: { year: 2019, month: 11 } }
];
let newArr= [];
arr.forEach(function (item) {
let isMatch = newArr.filter(function (elem) {
return elem._id.year === item._id.year
})
if (isMatch.length == 0) {
newArr.push(item)
}
else {
newArr.find(x => x._id.year === item._id.year)._id.month.push(...item._id.month);
}
})
console.log(newArr);