我想获取一个数组并确定其中有多少匹配元素,然后对它们进行计数以确定哪个元素具有最多相同的元素。
示例:
{% assign variable = "Cats|Dogs|Mice|Cats|Cats" | split:'|' %}
{% for v in variable %}
// Da-da-da, magic happens here, count matching elements.
{% endfor %}
{{ mostCommon }} // Return the most common element in array being Cats.
之前有人这样做过吗?我只是一名设计师所以我不能给出一个更好的例子:)
答案 0 :(得分:3)
所以我有点犹豫与你分享这一点......尤其是因为你如此清楚地表明你只是"只有"一个设计师(可能不想进入技术细节)。但既然你问过,这是我的解决方案。
{% assign array = "Cats|Dogs|Mice|Cats|Cats|Mice|Mice" | split:'|' %}
{% capture mostCommonString %}{% include most-occurences array=array %}{% endcapture %}
{% assign mostCommon = mostCommonString | split: "|" %}
{{ mostCommon | join: ", " }}
似乎很简单,对吧?不。您需要_include
文件夹中的以下代码才能为{% include %}
提供支持:
<强> _include /最OCCURENCES 强>
{% assign array = include.array %}{% assign setString = "" %}{% for elem in array %}{% unless setString contains elem %}{% assign setString = setString | append: '|' | append: elem %}{% endunless %}{% endfor %}{% assign set = setString | remove_first: '|' | split: '|' %}{% for x in array %}{% assign removedElements = "" %}{% for elem in set %}{% if array contains elem %}{% capture newArray %}{% include array-remove array=array remove=elem %}{% endcapture %}{% assign array = newArray | split: "|" %}{% assign removedElements = removedElements | append: '|' | append: elem %}{% unless array contains elem %}{% capture newSet %}{% include array-remove array=set remove=elem %}{% endcapture %}{% assign set = newSet | split: "|" %}{% endunless %}{% endif %}{% endfor %}{% assign arraySize = array | size %}{% if arraySize == 0 %}{% break %}{% endif %}{% endfor %}{{ removedElements | remove_first: "|" }}
这是主要的算法。基本上它:
还有一点:
<强> _include /阵列除去 强>
{% assign ret = "" %}{% assign removed = "false" %}{% for elem in include.array %}{% if elem == include.remove and removed != "true" %}{% assign removed = "true" %}{% continue %}{% endif %}{% assign ret = ret | append: "|" | append: {{elem}} %}{% endfor %}{{ ret | remove_first: "|" }}
这是一个很小的(相对)算法,可以从数组中删除第一次出现的字符串。
只是一个警告:很多算法都依赖于使用|
作为分隔符。我正在处理使用&
的{{3}},可以使用| escape
过滤器进行转义,但我并不认为这是一个问题。
不幸的是,所有空格必须才能移除以帮助{% capture %}
a version。
答案 1 :(得分:0)
这是您可以单行执行的操作
{% assign array = "Cats|Dogs|Mice|Cats|Cats|Mice|Mice|Dog" | split: '|' %}
{% assign grouped_elements = array | group_by: tag | sort: 'size' | reverse %}
{% assign highest_count = grouped_elements[0].size %}
{% for elem in grouped_elements %}
{% if elem.size == highest_count %}
{{ elem.name }} {{ elem.size }}
{% else %}
{% break %}
{% endif %}
{% endfor %}
// output
Mice 3
Cats 3
基本上我们正在做的是:
group_by
size
键对其排序