I am currently facing a challenge in grouping an array of objects by their respective years.
To provide some context, I have a visually appealing horizontal timeline graph created using D3js. My goal is to group events with overlapping dates by the year they occur in.
Here's an example of the data I am working with:
[
{times: [{color: 'red', year: 2031}]},
{times: [{color: 'green', year: 2031}]},
{times: [{color: 'blue', year: 2031}]},
{times: [{color: 'purple', year: 2045}]},
{times: [{color: 'orange', year: 2045}]},
]
The desired output format should be as follows (events grouped by year):
[
{times: [
{color: 'red', year: 2031},
{color: 'green', year: 2031},
{color: 'blue', year: 2031}
]},
{times: [
{color: 'purple', year: 2045},
{color: 'orange', year: 2045}
]}
]
I have attempted various approaches using reduce
, but haven't been successful in achieving the required data structure:
data.reduce((result: any, current: any) => {
const year = current.times[0].year;
/* I'm unsure how to proceed with the 'year' variable at this point */
result.push({ times: current.times[0] });
return result;
}, [{ times: [{}] }]);
Could you offer guidance on the refactoring needed to attain the desired data format?