Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

groupby changes order of an array if values are integers #1434

Open
Brixy opened this issue Feb 13, 2023 · 1 comment
Open

groupby changes order of an array if values are integers #1434

Brixy opened this issue Feb 13, 2023 · 1 comment

Comments

@Brixy
Copy link

Brixy commented Feb 13, 2023

Hi all,

if you take this example from the Nunjucks website …

{% set items = [
        { name: 'james', type: 'green' },
        { name: 'john', type: 'blue' },
        { name: 'jim', type: 'blue' },
        { name: 'jessie', type: 'green' }
    ]
%}

{% for type, items in items | groupby("type") %}
    <b>{{ type }}</b> :
    {% for item in items %}
        {{ item.name }}
    {% endfor %}<br>
{% endfor %}

… the order of the array is respected: green comes before blue:

Output

green : james jessie
blue : john jim

But if you use integers (or even quoted integers) …

{% set items = [
        { name: 'james', type: 2 },
        { name: 'john', type: 1 },
        { name: 'jim', type: 1 },
        { name: 'jessie', type: 2 }
    ]
%}

… the output is sorted numerically:

Output

1 : john jim
2 : james jessie

Expected output

2 : james jessie
1 : john jim

Is this Nunjucks issue or the expected behavior? Is there a way to avoid sorting by integers?


A practical workaround: Values for year have to be strings here, for example 2023- (with trailing hyphen).

{% for year, posts in posts | groupby("year") %}
	<h2>{{ year | replace("-", "") }}</h2>
	{% for post in posts %}
		<article>{{ post.title }}</article>
	{% endfor %}
{% endfor %}

Thank you.

@NextThread
Copy link

hey, can I work on this issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants