【发布时间】:2019-07-22 19:08:40
【问题描述】:
我有多个具有字符串属性"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}
]
]
要求的输出
总数
[
{"CountType":"Volumes","ItemCount":5},
{"CountType":"Sheets","ItemCount":7},
{"CountType":"Photos","ItemCount":9},
{"CountType":"Boxes","ItemCount":5},
{"CountType":"Other","ItemCount":8}
]
更新:这是我尝试运行该功能的方式:
【问题讨论】:
-
你的
sumByProperty函数看起来不错。请告诉我们你是如何在输入端调用它的
标签: javascript arrays ecmascript-6