[英]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.