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

October Featured Tools

Humhub

Social network development starter kit.

Explore

Curated Stack

Build a curated directory of websites without or with code.

Explore

We Recommend...

Top products featured for the article.

GoatCounter

An open source web analytics platform available as a hosted service (free for non-commercial use) or self-hosted app.

Explore

Supabase

Create a backend in less than 2 minutes. Start your project with a Postgres Database, Authentication, instant APIs, Realtime subscriptions and Storage.

Explore

Uptime Robot

The world's leading uptime monitoring service.

Explore

Tinking

A Chrome extension that allows you to create a website scraper recipe by directly selecting a pages elements with your mouse.

Explore

Sponsored

See all Tools

A Little Extra Reading

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

See all Articles