我将尝试按年份对对象数组进行分组。
为了更好地理解,我有一个水平时间轴图表(D3js),需要按年份对重叠的日期进行分组。
以下是我的数据:
我正在尝试将它转换为以下格式(按年份分组):
我该如何重构上述代码以达到所需的数据格式?
为了更好地理解,我有一个水平时间轴图表(D3js),需要按年份对重叠的日期进行分组。
以下是我的数据:
[
{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}]},
]
我正在尝试将它转换为以下格式(按年份分组):
[
{times: [
{color: 'red', year: 2031},
{color: 'green', year: 2031},
{color: 'blue', year: 2031}
]},
{times: [
{color: 'purple', year: 2045},
{color: 'orange', year: 2045}
]}
]
我尝试使用几种不同的reduce
方法,但似乎无法得到我需要的数据格式:
data.reduce((result: any, current: any) => {
const year = current.times[0].year;
/* Not entirely sure what to do with 'year' here */
result.push({ times: current.times[0] });
return result;
}, [{ times: [{}] }]);
我该如何重构上述代码以达到所需的数据格式?