JavaScript groupby sum给出错误结果

时间:2020-08-26 16:48:27

标签: javascript group-by lodash

我有此词典列表,数据,我想应用分组依据,然后金额总和,但是我得到的截止日期为{{ 1}},而不是最终聚合中的2020-05-11 00:00:00+00

请指出我做错了什么地方。

输入数据:-

2020-05-17 00:00:00+00

预期结果:-

data = [
{start_date: "2020-05-11 00:00:00+00", end_date: "2020-05-17 00:00:00+00", id: "ola", amount: 10},
{start_date: "2020-05-11 00:00:00+00", end_date: "2020-05-17 00:00:00+00", id: "ola", amount: 2}
]

当前结果:-

start_date: "2020-05-11 00:00:00+00", end_date: "2020-05-17 00:00:00+00", amount: 12}

分组依据公式:-

start_date: "2020-05-11 00:00:00+00", end_date: "2020-05-11 00:00:00+00", amount: 12}

如果还有其他使用Javascript的解决方案,请提出建议。谢谢

2 个答案:

答案 0 :(得分:1)

因为要链接data,所以下一个groupBy只需要采用一个参数(即doc中的变换键的迭代器

您可以设置start_dateend_date组合的组密钥

const data = [
  {
    start_date: "2020-05-11 00:00:00+00",
    end_date: "2020-05-17 00:00:00+00",
    id: "ola",
    amount: 10,
  },
  {
    start_date: "2020-05-11 00:00:00+00",
    end_date: "2020-05-17 00:00:00+00",
    id: "ola",
    amount: 2,
  },
]

const result = _(data)
  .groupBy((obj) => [obj.start_date, obj.end_date].join("to"))
  .map((value, key) => ({
    start_date: key.split("to")[0],
    end_date: key.split("to")[1],
    amount: _.sumBy(value, "amount"),
  }))
  .value()

console.log(result)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>

答案 1 :(得分:1)

使用开始和结束作为键的简单化简循环

data = [{
    start_date: "2020-05-11 00:00:00+00",
    end_date: "2020-05-17 00:00:00+00",
    id: "ola",
    amount: 10
  },
  {
    start_date: "2020-05-11 00:00:00+00",
    end_date: "2020-05-17 00:00:00+00",
    id: "ola",
    amount: 2
  }
]


const groupIt = data => {
  const groupings = data.reduce((grps, item) => {
    const { start_date, end_date, amount } = item;
    const key = `${start_date}-${end_date}`;
    grps[key] = grps[key] || { start_date, end_date, amount: 0 };
    grps[key].amount += amount;
    return grps;
  }, {});
  return Object.values(groupings);
}

const result = groupIt(data);
console.log(result);