如何解决按姓氏排序
我正在管理一个静态博客,里面有很多人的名字。我需要按照姓氏的字母顺序对他们进行排序。如果名字是一个字符串,如何按照姓氏排序?例如:
{% assign People = "John Smith,Foo Bar,Zee Mack Arlington" | split: "," %}
<!-- How do I sort People by last name -->
{% assign sortedPeople = People | sort_natural %}
{% for person in sortedPeople %}
<p>{{ person }}</p>
{% endfor %}
这给了我一个按名字按字母顺序排序的人的名单,但我需要按姓氏排序。
Foo Bar
Zee Mack Arlington
John Smith
解决方法
液体在设计上有一定的限制,但这是一种实现方式:
{% assign sorted_names = "" | split: "" %}
{% assign names_prefixed_with_last = "" | split: "" %}
{% assign names = "John Smith,Foo Bar,Zee Mack Arlington" | split: "," %}
{% for name in names %}
{% assign name_parts = name | split: " " %}
{% assign last_name = name_parts | last %}
{% assign name_prefixed_with_last = name | prepend: last_name %}
{% assign names_prefixed_with_last = names_prefixed_with_last | push: name_prefixed_with_last %}
{% endfor %}
{% assign sorted_with_prefix = names_prefixed_with_last | sort %}
{% for name_with_prefix in sorted_with_prefix %}
{% assign name_parts = name_with_prefix | split: " " %}
{% assign last_name = name_parts | last %}
{% assign name = name_with_prefix | replace_first: last_name %}
{% assign sorted_names = sorted_names | push: name %}
{% endfor %}
{% for name in sorted_names %}
<p>{{ name }}</p>
{% endfor %}
这将输出:
<p>Zee Mack Arlington</p>
<p>Foo Bar</p>
<p>John Smith</p>
首先,我们使用拆分的空字符串技巧创建了两个数组,然后在数组中填充以姓氏为前缀的名称(例如“ SmithJohn Smith”)。然后我们对其进行排序,因为它将按照姓氏排序,然后使用已删除前缀的排序后前缀数组的值填充数组。
尽管我对问题范围没有任何其他了解,但是更好的方法可能是将其与其他内容一起排序并将其放入数据文件中。您也可以将它们存储在数组中,而不用存储一个笨拙的字符串。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。