I need to sum the second value of an array and group it based on the first value (year).
This is my array:
dataArray = [[2020,140],[2020,145],[2020,90],[2021,88],[2021,12]];
And this is my function:
var result = [];
dataArray.reduce(function (res, value) {
if (!res[value[0]]) {
res[value[0]] = [value[0], 0];
dataArray.push(res[value[0]]);
}
res[value[0]][1] += value[1];
return res;
}, {});
I need this result:
dataArray = [[2020,375],[2021,100]]
But I got strange result, I think based on sum of previous value.
Can someone help me? Thank you