Mahesh
Mahesh

Reputation: 1333

Javascript groupby sum giving wrong results

I have this list of dictionaries data I want to apply groupby and then do sum of amount but I am getting end_date as 2020-05-11 00:00:00+00 instead of 2020-05-17 00:00:00+00 in the final aggregation

Please suggest where I am doing wrong.

Input data :-

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

Expected result :-

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

Current Result :-

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

groupby formula :-

var result = _(data)
            .groupBy(x => x.start_date, y => y.end_date)
            .map((value, key) => ({start_date: key, end_date : key, amount: _.sumBy(value, 'amount')}))
            .value();

If there is any other solution with Javascript, Please suggest. Thanks

Upvotes: 1

Views: 58

Answers (2)

epascarello
epascarello

Reputation: 207527

Simple reduce loop using start and end as the key

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);

Upvotes: 1

hgb123
hgb123

Reputation: 14891

Because you are chaining data, so the next groupBy just have to take one param (which is The iteratee to transform keys in the doc)

You could make group key of combination of start_date and end_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/[email protected]/lodash.min.js"></script>

Upvotes: 1

Related Questions