More Articles

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.

Written on May 6, 2024 | About 1 min reading time

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 }}.

March Featured Tools

Glorify

Easily create high converting product images fast and at scale. No design skills needed! Create store ready, high quality eCommerce images in just 3 steps.

Explore

Smart Mockups

Create stunning product mockups easily and online.

Explore

We Recommend...

Top products featured for the article.

Kiosk

Set up and handle all your office screens from one place. Group content and change displays with just a few clicks.

Explore

OpenBase

Compare open-source packages with powerful metrics and user reviews.

Explore

ScaffoldHub

The javascript/typescript full-stack web application generator.

Explore

Google Optimize

Whether it is a custom-tailored message at checkout or a completely revamped homepage, Optimize shows you which site experiences engage and delight your customers, and gives you the solutions you need to deliver them.

Explore

Sponsored

See all Tools

A Little Extra Reading

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

See all Articles