How to assign custom property to each item in an array?

What I am trying to do is

  • For every item post in array site.posts
    • Assign a custom property sort_date with the value of property last_modified_at
    • If last_modified_at does not exist, assign with date instead
  • Sort all the post in array site.posts by sort_date

I wrote the codes below, but it didn’t sort the posts as expected. Can anyone help me with it?

{%-assign posts = site.posts-%}
{%-for post in posts-%}
    {%-assign sort_date = last_modified_at | default: date-%}
{%- endfor -%}
{%- assign posts = posts | sort: "sort_date" -%}
<ul>
  {%- for post in posts-%}
      <li><a href="{{ post.url | relative_url }}">{{ post.title }}</a></li>
  {%- endfor -%}
</ul>
1 Like

I don’t think you can modify an array like that - but maybe you could make a new array that contains the url, title and sort date? then sort it and loop over it?

seems like your default date needs to be post.date?

See this: