我试图按年份对一组对象进行分组。
对于上下文,我有一个水平时间线图(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: [{}] }]);
如何重构以上内容以获得所需的数据形状?
最佳答案
您可以通过使用正确的year
查找嵌套对象来减少数组。
var data = [{ 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 }] }],
result = data.reduce((r, { times: [data] }) => {
var temp = r.find(({ times: [{ year }] }) => year === data.year);
if (temp) temp.times.push(data);
else r.push({ times: [data] });
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }