naregkar
naregkar

Reputation: 443

Count unique objects that meet certain criteria

[
    {
        "user": "PersonA",
        "status": "Done",
        "date": "2021-05-10T12:38:09Z"
    },
    {
        "user": "PersonA",
        "status": "Rejected",
        "date": "2021-05-15T11:08:41Z"
    },
    {
        "user": "PersonB",
        "status": "Rejected",
        "date": "2021-05-15T15:23:49Z"
    },
    {
        "user": "PersonA",
        "status": "Rejected",
        "date": "2021-05-15T18:51:04Z"
    },
    {
        "user": "PersonC",
        "status": "Done",
        "date": "2021-05-19T14:43:12Z"
    },
    {
        "user": "PersonB",
        "status": "Done",
        "date": "2021-05-19T19:29:10Z"
    },
    {
        "user": "PersonA",
        "status": "Done",
        "date": "2021-05-22T10:40:31Z"
    }
]

My API call returns the above JSON in Bash (in chronological order).

The algorithm should look for each user having the most recent date which has the status Done.

In case the most recent entry is of status Rejected (even if there are Done statuses before it), do not count it.

For the above JSON, the algorithm should return 3.

Note: the person count is not fixed, there may be n number of persons with n number of entries.

Any clue how to achieve this in Bash using jq or any other method?

Upvotes: 0

Views: 53

Answers (1)

oguz ismail
oguz ismail

Reputation: 50795

JQ can do this alone.

group_by(.user) | map(select(max_by(.date) .status == "Done")) | length

Online demo

Upvotes: 3

Related Questions