[英]Cumulative sum of values belonging to a same field in an array
我有一个以下格式的数组,该数组具有带数据字段的 x 和 y 值,我希望将其转换为一个数组,该数组将特定数据上的所有单个值相加,然后显示一个累积值(对该日期求和然后将值添加到以前的日期)。 例如。
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_data = [
{xvalue: 20, yvalue: 10, date: "12/2"}
{xvalue: 38, yvalue: 18, date: "12/3"}
{xvalue: 64, yvalue: 22, date: "12/4"}
]
有什么方法可以有效地做到这一点? 目前我有以下工作方式,但感觉它不是最好的实现
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;
}
}
data_array = [ {xvalue: 10, yvalue: 5, date: "12/2"}, {xvalue: 10, yvalue: 5, date: "12/4"}, {xvalue: 8, yvalue: 3, date: "12/3"}, {xvalue: 10, yvalue: 5, date: "12/2"}, {xvalue: 6, yvalue: 1, date: "12/3"}, {xvalue: 20, yvalue: 3, date: "12/2"}, ]; var reduced = data_array.reduce(function(final,item){ if(final[item.date]){ final[item.date] = {cummxvalue: item.xvalue+final[item.date].cummxvalue, cummyvalue: item.yvalue+final[item.date].cummyvalue, date: item.date}; }else{ final[item.date] = {cummxvalue: item.xvalue, cummyvalue: item.yvalue, date: item.date}; } return final; },{}); var new_data = Object.values(reduced); console.log(new_data);
您可以遍历数组并添加xvalue
s 和yvalue
,如果元素没有相同的date
值,则yvalue
复制到新数组中。 您还需要对数组进行排序,以防它尚未作为您的第一个示例进行排序。
const data_array = [ {xvalue: 10, yvalue: 5, date: "12/2"}, {xvalue: 10, yvalue: 5, date: "12/4"}, {xvalue: 8, yvalue: 3, date: "12/3"}, {xvalue: 10, yvalue: 5, date: "12/2"}, {xvalue: 6, yvalue: 1, date: "12/3"}, {xvalue: 20, yvalue: 3, date: "12/2"} ] let new_data = []; let cummxvalue = 0; let cummyvalue = 0; data_array.sort( (a, b) => a.date > b.date ); for( const obj of data_array) { let o = new_data.find(o => o.date === obj.date); cummxvalue += obj.xvalue; cummyvalue += obj.yvalue; if(!o) { new_data.push({cummxvalue: cummxvalue, cummyvalue: cummyvalue, date: obj.date}); } else { o.cummxvalue = cummxvalue; o.cummyvalue = cummyvalue; } } console.log(new_data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.