首页 > 解决方案 > 使用reduce获取对象的总和

问题描述

我想汇总 selectedIds 数组中的所有详细信息。

return [
      {
        id: 1244,
        name: "Installment 1",
        amount: 10000,
        due_date: new Date(),
        particulars: [
          {
            id: 2415123,
            name: "Development Fee",
            amount: 5000,
          },
          {
            id: 14123,
            name: "Library Fee",
            amount: 3000,
          },
          {
            id: 5123151,
            name: "Sports Fee",
            amount: 2000,
          },
        ]
      },
      {
        id: 1412,
        name: "Installment 2",
        amount: 6000,
        due_date: new Date(),
        particulars: [
          {
            id: 414,
            name: "Development Fee",
            amount: 5000,
          },
          {
            id: 5123,
            name: "Library Fee",
            amount: 3000,
          },
          {
            id: 515151,
            name: "Sports Fee",
            amount: 2000,
          },
        ]
const selectedIds = [14123, 414];

在对象中,我想要对 selectedIds 数组中的所有细节进行总和。我试图使用数组函数来获得结果。这是我能想到的。

const selectedInstallments = this.studentInstallments
        .filter((installment) =>
          installment.particulars.some((particular) =>
            this.selectedParticulars.includes(particular.id)
          )
        )
        .map((installment) => installment.particulars);
      console.log(selectedInstallments);
      const sumParticularReducer = (acc, current) => {
        return acc;
      };

我不知道如何使用 reduce 来获得结果。

标签: javascriptarrays

解决方案


请尝试此代码。

const selectedIds = [14123, 414];
const sum = arr.reduce((prev, cur) => {
    return prev + cur.particulars.reduce((old, item) => (
        selectedIds.indexOf(item.id) >= 0 ? old + item.amount : old
    ), 0);
}, 0);

console.log(sum);

推荐阅读