I have an array of objects with different years and details
var worksSummaryDetailsArr = [
{
year: 2020,
worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ]
},
{
year: 2021,
worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ]
},
{
year: 2022,
worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ]
},
{
year: 2021,
worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ]
},
{
year: 2022,
worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ]
}
]
My goal is to merge the array based on the same year while concatenating the worksSummaryDetailsObj together
{
year: 2020,
worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ]
},
{
year: 2021,
worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object],[Object], [Object], [Object], [Object] ]
},
{
year: 2022,
worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object],[Object], [Object], [Object], [Object] ]
},
Although I attempted to achieve this using the set function and mapping with the same year, I encountered issues with incorrect data in worksSummaryDetailsObj
Below is the code snippet I tried:
const r = [...new Set(worksSummaryDetailsArr.map((i) => i.year))].map((i) => ({
year: i,
worksSummaryDetailsObj: [...new Set(worksSummaryDetailsArr.filter(({ year: c }) => c === i))],
}));
console.log(r);