我有日期数组,我想按年份对日期进行分组并减去最后一个值 - 第一个值。例如,我有以下数组:
const data = [
{ x: "2021-10-17T14:38:45.540Z", y: 2 },
{ x: "2021-10-17T13:38:45.540Z", y: 2 },
{ x: "2021-09-16T14:36:46.540Z", y: 1 },
{ x: "2021-01-04T14:35:46.540Z", y: 2 },
{ x: "2021-01-01T14:30:46.540Z", y: 1 },
{ x: "2020-02-01T06:28:47.520Z", y: 12 },
{ x: "2020-02-01T07:28:47.520Z", y: 12 },
{ x: "2019-04-13T10:19:20.034Z", y: 20 },
{ x: "2018-01-01T09:09:19.134Z", y: 4 },
{ x: "2017-01-01T12:09:19.034Z", y: 11 },
{ x: "2016-01-02T12:10:20.034Z", y: 24 },
{ x: "2016-01-02T11:10:20.034Z", y: 14 }
];
这就是我尝试按年对对象分组数组并减去最后一个值 - 第一个值
我得到了这个结果,它总结了这些值:
[
{
"value": 8,
"label": "2021"
},
{
"value": 24,
"label": "2020"
},
{
"value": 20,
"label": "2019"
},
{
"value": 4,
"label": "2018"
},
{
"value": 11,
"label": "2017"
},
{
"value": 38,
"label": "2016"
}
]
年度预期产出(值 = 最后一个值 - 第一个值):
[
{
"value": 1,
"label": "2021"
},
{
"value": 0,
"label": "2020"
},
{
"value": 20,
"label": "2019"
},
{
"value": 4,
"label": "2018"
},
{
"value": 11,
"label": "2017"
},
{
"value": 10,
"label": "2016"
}
]
这是按年分组的功能:
function group_by_year(arr) {
return Object.values(
arr.reduce((a, { x: date_string, y: value }) => {
const { year } = get_date_parts(date_string);
if (a[year] === undefined) {
a[year] = { value: 0, label: year };
}
a[year].value += value; // the problem (lastValue - firstValue)
return a;
}, {})
);
}
问题是如何将此行更改a[year].value += value;
为a[year].value = lastValue - firstValue;