Skip to main content

How to shuffle an array in a Jekyll template

If you want an array in random order, you can use the sample filter to get a random sample of the same size as the original array.

As part of the site rebuild, I wanted a way to shuffle a list of selected articles at build time. This order will get “baked in” to the rendered output, but it still introduces an element of randomness and I rebuild the site once a day anyway.

It turns out there’s no way to do this in vanilla Liquid, but Jekyll has a sample filter that can pick one or more random values from an array:

{% assign fruits = "apple,banana,cherry,damson" | split: "," %}
{% assign fruits = fruits | sample: fruits.size %}

{% for f in fruits %}
  {{ f }}
{% endfor %}

If you look at the implementation, this is just a thin wrapper about Array.sample, and it has similar behaviour – e.g. no duplicates, never returns more than the original array.