gpt4 book ai didi

Javascript ES6 计算对象数组的总和

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:56:30 25 4
gpt4 key购买 nike

我有多个对象数组,它们具有字符串属性 "CountType" 和数字属性 "ItemCount"

必须通过"CountType" 属性将对象相加以计算所有项目的总数。

例如,我需要知道 Volumes、Sheets、Photos 等的总数。

尝试 #1:我尝试的这段代码返回 0。这可能是因为我需要循环遍历外部数组以对嵌套数组进行比较。

function sumByProperty(items, prop) {
if (items == null) {
return 0;
}
return items.reduce(function (a, b) {
return b[prop] == null ? a : a + b[prop];
}, 0);
}

输入

项目数

[
[
{"CountType":"Volumes","ItemCount":3},
{"CountType":"Sheets","ItemCount":6},
{"CountType":"Photos","ItemCount":3},
{"CountType":"Boxes","ItemCount":1},
{"CountType":"Other","ItemCount":2}
],
[
{"CountType":"Volumes","ItemCount":1},
{"CountType":"Sheets","ItemCount":1},
{"CountType":"Photos","ItemCount":3},
{"CountType":"Boxes","ItemCount":0},
{"CountType":"Other","ItemCount":1}
],
[
{"CountType":"Volumes","ItemCount":1},
{"CountType":"Sheets","ItemCount":0},
{"CountType":"Photos","ItemCount":3},
{"CountType":"Boxes","ItemCount":4},
{"CountType":"Other","ItemCount":5}
]
]

DEISRED 输出

总计数

[
{"CountType":"Volumes","ItemCount":5},
{"CountType":"Sheets","ItemCount":7},
{"CountType":"Photos","ItemCount":9},
{"CountType":"Boxes","ItemCount":5},
{"CountType":"Other","ItemCount":8}
]

更新:这是我尝试运行函数的方式:

https://jsfiddle.net/yd051o76/2/

最佳答案

Possibly that is because I need to loop through the outer array to do the comparison across the nested arrays.

事实上,您可以展平数组:

 function sumByProperty(items, prop) {
return items.flat().reduce(function (a, b) {
return b[prop] == null ? a : a + b[prop];
}, 0);
}

const result = [
{ CountType: "Volumes", ItemCount: sumByProperty(input, "Volumes"), },
//...
];

但我宁愿使用哈希表进行动态分组,这样您只需迭代一次,而无需命名所有属性:

  const hash = new Map();

for(const { CountType, ItemCount } of input.flat())
hash.set(CountType, (hash.get(CountType) || 0) + ItemCount);

const result = [...hash.entries()].map(([CountType, ItemCount]) => ({ CountType, ItemCount }));

关于Javascript ES6 计算对象数组的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57152330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com