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

时间:2017-12-20 14:07:27

标签: javascript arrays

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

[
  {
     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
   }
 ]

1 个答案:

答案 0 :(得分: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