Hi,
Is there a built-in function to retrieve the position of a given string in an array?
For example
{% assign Arr_A = ‘A|B|C|D’ | split: ‘|’ %}
{% assign LetterToSearch = ‘C’ %}
=> so the result of the function should be 2 (position of ‘C’ in Arr_A)?
Thanks!
sven
April 11, 2018, 1:34pm
2
Hi @Bart_Verhaeghe ,
There’s not really a function in Liquid for that, it seems.
But, with some tweaking, you could go for something similar to this:
{% assign my_array = "apples|oranges|peaches|plums" | split: "|" %}
{% assign value_element = 0 %}
{% input custom.search.element %}
{% for item in my_array %}
{% assign value_element = value_element | plus:1 %}
{% if custom.search.element == item %}
{% break %}
{% endif %}
{% endfor %}
test = {{ value_element }}
Could use some tweaking I think. Do you see something in this? The break
tag will stop the forloop as soon as the if-statement is done.
sven:
{% assign my_array = “apples|oranges|peaches|plums” | split: “|” %}
{% assign value_element = 0 %}
{% input custom.search.element %}
{% for item in my_array %}
{% assign value_element = value_element | plus:1 %}
{% if custom.search.element == item %}
{% break %}
{% endif %}
{% endfor %}
test = {{ value_element }}
OK thanks Sven (you’re a genius!). I tweaked it a bit by comparing value_element with the size of the array in case the string does not appear in the array, but for the rest I copied your solution. Thanks!
1 Like