Randomize Collections with a Custom Shuffle Filter in Eleventy

Learn how to create a custom 'shuffle' filter in Eleventy to randomly reorder arrays and collections in your templates.

New tools in your inbox every Monday!

Table of Contents

Shuffling Collections with a Custom Filter in Eleventy

In Eleventy, you can create custom filters to extend the functionality of the templating system. One useful custom filter is a "shuffle" filter that randomizes or shuffles an array of items or collections. Here's how you can implement it:

  
  // Shuffle / randomize array 
  config.addFilter("shuffle", function(array) {
      // Create a copy of the array to avoid modifying the original
      let shuffledArray = array.slice();

      // Fisher-Yates shuffle algorithm
      for (let i = shuffledArray.length - 1; i > 0; i--) {
          const j = Math.floor(Math.random() * (i + 1));
          [shuffledArray[i], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i]];
      }

      return shuffledArray;
  });

This custom filter uses the a shuffle algorithm to randomly rearrange the elements in the array. It first creates a copy of the original array to avoid modifying it. Then, it iterates through the array from the end to the beginning, swapping each element with a randomly selected element from the remaining unshuffled elements.

To use this custom filter in your Eleventy templates, simply pass your array or collection to the "shuffle" filter like this: {{ myCollection | shuffle }}.

May Featured Tools

Invoicely

Free invoice generator, invoice templates online.

Explore

Merkle SEO Tools

SEO Tools & Insights from Merkle, a performance marketing agency.

Explore

We Recommend...

Top products featured for the article.

Lenis JS

A new smooth scroll library fresh out of the Studio Freight Darkroom.

Explore

Synthesia

Create professional AI videos from text in 60+ languages.

Explore

Publii

Publii is a desktop-based CMS for Windows, Mac and Linux that makes creating static websites fast and hassle-free, even for beginners.

Explore

Niceboard

Start your own profitable job board and unlock the value in your audience.

Explore
See all Tools

A Little Extra Reading

Feel like reading more? Here are some extra articles to check out!

See all Articles