fluid icon indicating copy to clipboard operation
fluid copied to clipboard

Add custom filter group_by

Open arthurmmedeiros opened this issue 1 year ago • 3 comments

Hello there,

I previously added this question, but I realised the code I wrote was just wrong. I fixed it and decided to create a pull request with this new custom filter.

I think this is a useful feature, so I felt I could share and give a small contribution to this library.

I added some tests and I'm happy to add more if necessary.

Thank you.

arthurmmedeiros avatar Aug 26 '24 04:08 arthurmmedeiros

What's the problem that you going to fix?

hishamco avatar Aug 26 '24 18:08 hishamco

@hishamco sorry, I should have given more details about this pull request in my first comment.

The problem I am trying to solve is to group a list of objects by a certain key. In the tests I used an example where I had a list of users, and I wanted to group these users by type (admin and client).

I hope this makes more sense.

arthurmmedeiros avatar Aug 26 '24 23:08 arthurmmedeiros

@sebastienros do you have any objection to introduce this filter, before I review

hishamco avatar Aug 27 '24 00:08 hishamco

Hi, are there any updates? Grouping would be great.

Lifree avatar Feb 26 '25 09:02 Lifree

grouping would also be useful for our use case

especially some complex cases like {% assign osVersions = model.Variants | group_by: 'CustomFields["97f9af79-a4ea-4766-8eac-b61da5d89de7"].Value' %}

yegorandrosov avatar Apr 03 '25 16:04 yegorandrosov

I looked into it since there is not such thing by default in Liquid, why there isn't and how people do without it. Found a straightforward solution. Here is an example:

{% assign ages = people | map: 'age' | uniq %}
{%- for age in ages %}
  {%- assign people_by_age = people | where: 'age', age | sort: 'name' %}
  {%- for person in people_by_age %}
  {{ person.age }} {{ person.name }}
  {%- endfor%}
{%- endfor%}

Playground

I am not opposed to adding special filters eithers, but this would have to be opt-in via the FluidOptions, and documented as non-standard.

NB: I believe we can use filters directly in the loop too, which would prevent assign tags, but TBC.

sebastienros avatar Apr 03 '25 19:04 sebastienros

@sebastienros thanks a lot i think indexer does not work with map filter? but i figured out that dot works

{% assign osVersions = model.Variants | map: 'CustomFields.97f9af79-a4ea-4766-8eac-b61da5d89de7.Value' | uniq %}

yegorandrosov avatar Apr 04 '25 07:04 yegorandrosov