Search code examples
javascriptangulartypescriptunderscore.jslodash

Typescript/Lodash group by -- Trying to group values of a key of an array with their quantity


Code:

    this.countSmth = _(data).groupBy('DeliveryStatus').values().map(
      (group) => ({ ...group[0], qty: group.length })
    ), console.log(this.countSmth);

I've been experimenting with this stackblitz and all works well, giving me the desired result. However in my project the end result looks like this(link).

The HTTP response that I'm using as a source looks like this:

{
    {
        "BookingId": "VALUE",
        "OrderNumber": "VALUE",
        "ArrivalTime": "VALUE",
        "DepartureTime": "VALUE",
        "Duration": "VALUE",
        "DeliveryStatus": "Accepted"
    }
]

In my Angular project Ive used yarn to add 'lodash' and @types/lodash. I decided to test the same stackblitz text in the same environment and it dosn't seem to work which means I've written it wrong there.

EDIT: I've created an angular project and imported lodash the same. I replaced the data object that I'm getting with a typed array, here:

https://stackblitz.com/edit/angular-qbpnqc


Solution

  • After 8 hours of troubleshooting and some help in another thread + some help from colleagues, I ended up with this function:

      let countUniqueValues = (data, key) => {
        return _(data).groupBy(key).values().map(
          (group) => ({ key: group[0][`${key}`], count: group.length })
        ).value()
      }
    

    Now, when I update my store, I can call this function to create any kpi I want by passing it the data from the action and the key whose values I want to count.

    I don't even have to touch the function at all.