Group By id和Sum使用Lodash得到新的总和

问题描述 投票:-1回答:1

是否可以通过(例如,“id”)进行排序和分组,并通过使用Lodash添加密钥的所有唯一值(例如:支付)来更新元素的值? 例如,这个数组可以在下面:

[
  {
     id: 1,
     payout: 15,
     numOfPeople: 4
  },
  {
     id: 1,
     payout: 12,
     numOfPeople: 3
  },
  {
     id: 2,
     payout: 6,
     numOfPeople: 5
  },
  {
     id: 2,
     payout: 10,
     numOfPeople: 1
  }
]

...使用LODASH转换成下面的那个:

  // Notice the Sum of all payout reflects the total sum of all
  // payout with id=1 or id=2 (for a specific id Group)

[
  {
     id: 1,
     payout: 27,
     numOfPeople: 4
  },
  {
     id: 1,
     payout: 27,
     numOfPeople: 3
  },
  {
     id: 2,
     payout: 16,
     numOfPeople: 5
  },
  {
     id: 2,
     payout: 16,
     numOfPeople: 1
   }
 ]
javascript arrays
1个回答
0
投票

你可以使用filtermapreduce的组合来做到这一点。

const arr = [
  {
    id: 1,
    payout: 15,
    numOfPeople: 4,
  },
  {
    id: 1,
    payout: 12,
    numOfPeople: 3,
  },
  {
    id: 2,
    payout: 6,
    numOfPeople: 5,
  },
  {
    id: 2,
    payout: 10,
    numOfPeople: 1,
  },
];

const idPayoutMap = {};

let result = arr.map(x => {
  if (idPayoutMap['' + x.id] !== undefined) {
    x.payout = idPayoutMap['' + x.id];
  } else {
    x.payout = arr
      .filter(y => y.id === x.id)
      .reduce((totalPayout, y) => y.payout + totalPayout, 0);
    idPayoutMap['' + x.id] = x.payout;
  }

  return x;
});


console.log(result);

这是一个工作样本:Sample

© www.soinside.com 2019 - 2024. All rights reserved.