JS如何对包含多个数值的数组使用reduce
JS How to use reduce on array containing multiple numerical values
我有一个这样的数组。
[{
PropertyOne : 1,
PropertyTwo : 5
},
{
PropertyOne : 3,
PropertyTwo : 5
},...]
我想要一个这样的数组它聚集了这个数组的所有列,最终像这样
[{
PropertyOne : 4,
PropertyTwo : 10
}}
如果是单列,我知道我可以使用。reduce,但是我不知道如何使用多列。
var array = [{
PropertyOne : 1,
PropertyTwo : 5
},
{
PropertyOne : 2,
PropertyTwo : 5
}];
var reducedArray = array.reduce(function(accumulator, item) {
// loop over each item in the array
Object.keys(item).forEach(function(key) {
// loop over each key in the array item, and add its value to the accumulator. don't forget to initialize the accumulator field if it's not
accumulator[key] = (accumulator[key] || 0) + item[key];
});
return accumulator;
}, {});
使用ES6箭头函数相同(与其他答案相同):
var reducedArray = array.reduce((accumulator, item) => {
Object.keys(item).forEach(key => {
accumulator[key] = (accumulator[key] || 0) + item[key];
});
return accumulator;
}, {});
相关文章:
- 对一个对象使用reduce可以返回一个没有't在数组中包含目标字母
- 如果数组中只有一个对象,则Lodash返回错误的reduce结果
- 使用JavaScript's Reduce从对象数组创建数组
- 使用JavaScript映射reduce从数组中删除项
- 使用 reduce 函数返回数组
- 使用 reduce 确定数组中最小数的索引
- 如果对象使用 reduce、forEach 或筛选器共享属性值,则合并 JSON 数组中的对象
- 在数组#reduce中设置初始值与不设置初始值
- 如何仅在数组的某些第一个元素上使用_.reduce
- 为什么这个map reduce Promises数组不起作用,而只是减少它起作用
- 使用reduce来缩短数组
- 在数组数组的map()中使用reduce()
- 使用javascript中的reduce函数查找数组的最小和最大数
- 使用reduce检查数组是否包含与字符串匹配的正则表达式
- 使用reduce (javascript)在数组中添加数字对
- 数组上的Reduce方法-它是如何工作的
- 使用reduce方法处理数组元素
- Javascript-使用reduce来反转数组
- 使用javascript数组.Reduce删除重复项
- 在数组reduce中显式传递未定义的初始值