I have an array in the following format that has x and y values with a data field and I am looking to convert into an array that adds up all the individual value over a specific data, and then shows a cumulative value (summing over that date and then adding the value to the previous dates). Eg.
data_array = [
{xvalue: 10, yvalue: 5, date: "12/2"},
{xvalue: 10, yvalue: 5, date: "12/2"},
{xvalue: 8, yvalue: 3, date: "12/3"},
{xvalue: 10, yvalue: 5, date: "12/3"},
{xvalue: 6, yvalue: 1, date: "12/4"},
{xvalue: 20, yvalue: 3, date: "12/4"},
]
New array
new_data = [
{xvalue: 20, yvalue: 10, date: "12/2"}
{xvalue: 38, yvalue: 18, date: "12/3"}
{xvalue: 64, yvalue: 22, date: "12/4"}
]
What will be a way to do this efficiently? Currently I have the following way that works but feel like its not the best implementation
var temp = {}
var obj = null
for (var i=0; i<data_array.length; i++){
obj = data_array[i];
if (!temp[obj.date]) {
temp[obj.date]=obj;
}
else {
temp[obj.date].xvalue += obj.xvalue;
temp[obj.date].yvalue += obj.yvalue
}
}
var result = [];
for (var prop in temp){
result.push(temp[prop]);
}
console.log("result", result)
for (var i=0; i< result.length; i++){
if (i!=0){
result[i].xvalue +=result[i-1].xvalue;
result[i].yvalue +=result[i-1].yvalue;
}
}