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

July Featured Tools

Alli AI

Automate SEO at Scale. Make thousands to millions of code and content changes in minutes. Manage all your SEO from one dashboard.

Explore

Luna Task

An all-in-one privacy-focused todo list, notebook, habit and mood tracker, and pomodoro timer. It remembers stuff for you and knows what to work on next. Choose from a variety of productivity techniques to get stuff actually done.

Explore

We Recommend...

Top products featured for the article.

Copy.ai

Forget writers block. Get blog posts, ads, social media content, poems, business ideas and more by just clicking a button. Our bots will write everything for you.

Explore

Good Palette

Try out different color schemes on various UI layouts.

Explore

Deep Space Digital Marketing Group

Custom small to medium sized business website design, development, and digital management with an emphasis on lead generation. Starting at $199 per month with $0 down.

Explore

Name Panda

Generate a name for your SaaS product.

Explore

Sponsored

See all Tools

A Little Extra Reading

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

See all Articles