按年份对对象数组进行分组

4
我将尝试按年份对对象数组进行分组。
为了更好地理解,我有一个水平时间轴图表(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: [{}] }]);

我该如何重构上述代码以达到所需的数据格式?
1个回答

5

您可以通过查找具有正确 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; }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接