我只想根据年份计算总和值列,我的数据如下,但我不知道如何使用 Angular (在脚本中)或javascript来执行此操作。
[
{"Year":2013,"Product":"A","Value":0},
{"Year":2013,"Product":"B","Value":20},
{"Year":2013,"Product":"A","Value":50},
{"Year":2014,"Product":"D","Value":55},
{"Year":2014,"Product":"M","Value":23},
{"Year":2015,"Product":"D","Value":73},
{"Year":2015,"Product":"A","Value":52},
{"Year":2016,"Product":"B","Value":65},
{"Year":2016,"Product":"A","Value":88}
]
我想对“值”列执行求和,并删除“产品”列。 谢谢
最佳答案
编辑正如评论者所指出的,这甚至不需要 Lodash。在当前项目中使用 Lodash 太多了,我忘记了 reduce
是内置的。 :-)
还更新为将数据放入所需的形式[{"yyyy": xxxx},...]
。
此代码将完成此操作:
var data = [{"Year":2013,"Product":"A","Value":0},{"Year":2013,"Product":"B","Value":20},{"Year":2013,"Product":"A","Value":50},{"Year":2014,"Product":"D","Value":55},{"Year":2014,"Product":"M","Value":23},{"Year":2015,"Product":"D","Value":73},{"Year":2015,"Product":"A","Value":52},{"Year":2016,"Product":"B","Value":65},{"Year":2016,"Product":"A","Value":88}];
var sum = data.reduce(function(res, product){
if(!(product.Year in res)){
res[product.Year] = product.Value;
}else{
res[product.Year] += product.Value;
}
return res;
}, {});
result = [];
for(year in sum){
var tmp = {};
tmp[year] = sum[year];
result.push(tmp);
}
console.log(result);
结果:
[{"2013": 70}, {"2014": 78}, {"2015": 125}, {"2016": 153}]
原始答案
我能想到的最简单的方法是使用 Lodash图书馆。它为您提供了一些很好的函数式编程能力,例如 reduce
,它基本上将函数逐一应用于数组或集合的每个元素并累积结果。
在这种情况下,如果您使用 Lodash,则可以按如下方式完成此操作:
var data = [{"Year":2013,"Product":"A","Value":0},{"Year":2013,"Product":"B","Value":20},{"Year":2013,"Product":"A","Value":50},{"Year":2014,"Product":"D","Value":55},{"Year":2014,"Product":"M","Value":23},{"Year":2015,"Product":"D","Value":73},{"Year":2015,"Product":"A","Value":52},{"Year":2016,"Product":"B","Value":65},{"Year":2016,"Product":"A","Value":88}];
result = _.reduce(data, function(res, product){
if(!(product.Year in res)){
res[product.Year] = product.Value;
}else{
res[product.Year] += product.Value;
}
return res;
}, {});
这会产生:
{
"2013": 70,
"2014": 78,
"2015": 125,
"2016": 153
}
基本上,我们告诉 Lodash 的是我们想要一一遍历数据中的所有元素,对每个元素执行一些操作。我们将把这个操作的结果保存在一个名为 res
的变量中。最初,res
只是一个空对象,因为我们没有执行任何操作。当 Lodash 查看每个元素时,它会检查该产品的年份是否在 res
中。如果是,我们只需将 Value
添加到 res
中的那一年即可。如果不是,我们将 res
中的 Year 设置为当前产品的 Value
。这样我们就可以将每年的所有产品值(value)相加。
如果您想尝试一下,可以在这里进行: Online Lodash Tester
干杯!
关于javascript - 在 javascript 或 angularjs 中分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40641235/