arrays - 将一个数组的值与另一个数组相加
问题描述
如果我有一个像下面这样的数组,我可以得到金额的总和吗?
[{"_id":"5e154cf38c52231ee19f8",
"refunds":[
{"_id":"5e38f10a754fcf3d48015",
"reason":"refund 1",
"amount":50000,
]},
{"_id":"5e1578b48c52231ee19f8",
"refunds":[
{"_id":"5e37e09ef9ea5e3784043",
"reason":"refund 1",
"amount":100000,
{"_id":"5e37e12a02c27c14580a1",
"reason":"refund 2",
"amount":100000,
{"_id":"5e38f02b754fcf3d48015",
"reason":"refund 3",
"amount":50000,
]},
{"_id":"5e1578b48c52231ee19f8",
"refunds":[]
}]
我希望得到 res = 300000
解决方案
这应该相对简单,我们使用flatMap创建一个包含所有退款对象的平面数组,然后我们将使用reduce来求和总金额。
我添加了另一个函数 sumRefundAmountsII 来解决不支持.flatMap(ES2019 之前)的 JavaScript 环境
const data = [ { "_id": "5e154cf38c52231ee19f8", "refunds": [ { "_id": "5e38f10a754fcf3d48015", "reason": "refund 1", "amount": 50000 } ] }, { "_id": "5e1578b48c52231ee19f8", "refunds": [ { "_id": "5e37e09ef9ea5e3784043", "reason": "refund 1", "amount": 100000 }, { "_id": "5e37e12a02c27c14580a1", "reason": "refund 2", "amount": 100000 }, { "_id": "5e38f02b754fcf3d48015", "reason": "refund 3", "amount": 50000 } ] }, { "_id": "5e1578b48c52231ee19f8", "refunds": [] }];
function sumRefundAmounts(array) {
// Get an array of all refunds.
const refunds = array.flatMap(obj => obj.refunds);
// Sum amount for each refund.
return refunds.reduce((sum, refund) => {
return sum + refund.amount;
}, 0);
}
console.log("Total amount:", sumRefundAmounts(data));
// Use this function if your JavaScript environment complains about .flatMap
function sumRefundAmountsII(array) {
// Use a work around if we don't have flatMap...
const refunds = [].concat.apply([], array.map(obj => obj.refunds));
// Sum amount for each refund.
return refunds.reduce((sum, refund) => {
return sum + refund.amount;
}, 0);
}
console.log("Total amount (no flat map):", sumRefundAmountsII(data));
推荐阅读
- android - 颤振医生无法识别我的物理设备
- python - pip install colour-science 后颜色方法无法访问
- c# - Serilog 未记录到不同于错误的哨兵级别
- php - Prestashop - 如何将现有数据库迁移到新的 prestashop 项目?
- scala - 我如何在 Livy 0.7 上缩放 2.12
- python - python regex - findall 没有按预期返回输出
- php - PHP致命错误:未捕获的TypeError:无法访问字符串类型字符串的偏移量
- firebase - Google 身份验证自动登录
- sql-server - SQL Server 会自动为所有实例分配内存吗?
- javascript - Safari 的正则表达式后视替代方案