0

I am using 'lodash' groupBy method to group transactions by user_id:

Here is the the example of initial array:

{
      transaction_id: '2382697',
      user_id: '16239',
      transaction_label: 'IKEA',
      transaction_date: 2020-10-13T21:00:00.000Z,
      transaction_amount: -49
    },
{
      transaction_id: '2388400',
      user_id: '16231',
      transaction_label: 'ADEO',
      transaction_date: 2020-05-24T21:00:00.000Z,
      transaction_amount: -39.9
    },
    {
      transaction_id: '2388991',
      user_id: '16231',
      transaction_label: 'BRON',
      transaction_date: 2020-06-29T21:00:00.000Z,
      transaction_amount: -86.89
    }

Expected behavior of _.groupBy(array, 'user_id') is:

{
'16239': [
  {
      transaction_id: '2382697',
      user_id: '16239',
      transaction_label: 'IKEA',
      transaction_date: 2020-10-13T21:00:00.000Z,
      transaction_amount: -49
    }
],
'16231': [
  {
      transaction_id: '2388400',
      user_id: '16231',
      transaction_label: 'ADEO',
      transaction_date: 2020-05-24T21:00:00.000Z,
      transaction_amount: -39.9
    },
    {
      transaction_id: '2388991',
      user_id: '16231',
      transaction_label: 'BRON',
      transaction_date: 2020-06-29T21:00:00.000Z,
      transaction_amount: -86.89
    }
]
}

BUT! In the array, where more the 1 transaction, the first element is the transaction with cumulated transaction amount:

'16231': [
    {
      transaction_id: '2388400',
      user_id: '16231',
      transaction_label: 'ADEO',
      transaction_date: 2020-05-24T21:00:00.000Z,
      transaction_amount: -126.79
    },
    {
      transaction_id: '2388991',
      user_id: '16231',
      transaction_label: 'BRON',
      transaction_date: 2020-06-29T21:00:00.000Z,
      transaction_amount: -86.89
    }
  ],

Who can clarify this behavior? And how to avoid it ?

P.Shustenko
  • 93
  • 13
  • The grouping is correct. If you mean that the *order* is different - yes, it's how JavaScript orders keys. Any positive integer keys will be iterated in incrementing order. It's part of the specs. If you mean something else, I'm not really sure what it is. – VLAZ Nov 16 '20 at 18:44
  • @VLAZ it is ok for order. I don't care the order. Take a look at the output array ot transactions. The first element has -> transaction_amount: -126.79, but it should be like -> transaction_amount: -39.9. User with id 16231 has 2 transactions with amounts: -39.9 and - 86.89. But as you an see, the first element -126.79 = -39.9 - 86.89. This is the point i don't understand. – P.Shustenko Nov 16 '20 at 18:58
  • 2
    [I can't reproduce that](https://jsbin.com/xomeseyene/1/edit?js,console). My best guess is that your code *modifies* the objects later and [the console is lazy](https://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays), so you just see the updated values. – VLAZ Nov 16 '20 at 19:00

0 Answers0