首页 > 解决方案 > 将一个数组的值与另一个数组相加

问题描述

如果我有一个像下面这样的数组,我可以得到金额的总和吗?

[{"_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

标签: arraysnode.jssortingsum

解决方案


这应该相对简单,我们使用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));


推荐阅读