How to obtain a random value from a Liquid Array?

Chris_Sydney
Shopify Partner
86 4 15

Hey, 

 

Wodnering if anyone knows how to get a random value from a shopify array? 

 

I have tried "| shuffle" but that doesnt seem to work. 

 

Cheers, 

 

Chris 

Replies 4 (4)

ZestardTech
Shopify Expert
5436 978 1304

Hello @Chris_Sydney 

{% assign myArray = "item1, item2, item2, item2, item2" | split: ", " %}

{% comment %} Generate a random index using JavaScript and store it in a Liquid variable {% endcomment %}
{% assign randomIndex = "" %}
<script>
document.addEventListener("DOMContentLoaded", function() {
var arrayLength = {{ myArray | size }};
var randomIndex = Math.floor(Math.random() * arrayLength);
document.getElementById("random-index").innerText = randomIndex;
});
</script>

{% comment %} array using the random index {% endcomment %}
{% for item in myArray %}
{% if forloop.index0 == randomIndex %}
{{ item }}
{% endif %}
{% endfor %}
Want to modify or develop new app, Hire us.
If helpful then please Like and Accept Solution .
Email: support@zestard.com
Shopify Apps URL :- https://apps.shopify.com/partners/zestard-technologies
Custom Modifications Into Shopify Theme | Shopify Private App | SEO & Digital Marketing
Chris_Sydney
Shopify Partner
86 4 15

Hey ZestardTech, 

 

Awesome, thanks... I was trying to create a new a new value with | random, but looks like i need to use JS. 

 

Cheers,

 

Chris

ZestardTech
Shopify Expert
5436 978 1304

Hello @Chris_Sydney 

Working fine or not ?

Want to modify or develop new app, Hire us.
If helpful then please Like and Accept Solution .
Email: support@zestard.com
Shopify Apps URL :- https://apps.shopify.com/partners/zestard-technologies
Custom Modifications Into Shopify Theme | Shopify Private App | SEO & Digital Marketing
phil_CM
Explorer
85 1 10

Doesnt seem to work fo rme unless I need to be doing something more than copying and pasting..