按年份分组对象数组

wpe*_*per 4 javascript arrays typescript

我正在尝试按年份对一组对象进行分组。

对于上下文,我有一个水平时间线图 (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}]},
]
Run Code Online (Sandbox Code Playgroud)

并试图将其变成以下形状(按年份分组):

[
  {times: [
    {color: 'red', year: 2031},
    {color: 'green', year: 2031},
    {color: 'blue', year: 2031}
  ]},
  {times: [
    {color: 'purple', year: 2045},
    {color: 'orange', year: 2045}
  ]}
]
Run Code Online (Sandbox Code Playgroud)

我曾尝试使用一些变体,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: [{}] }]);
Run Code Online (Sandbox Code Playgroud)

我将如何重构上述内容以获得所需的数据形状?

Nin*_*olz 5

您可以通过找到具有 right 的嵌套对象来减少数组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);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)