11ty / eleventy

A simpler site generator. Transforms a directory of templates (of varying types) into HTML.
https://www.11ty.dev/
MIT License
16.91k stars 491 forks source link

Sort Custom Collections Randomly #997

Closed scottwater closed 4 years ago

scottwater commented 4 years ago

Any suggestions for sorting a collection randomly?

I thought this would work:

  eleventyConfig.addCollection("caps", collection => {
    return collection.getFilteredByTag("gmk").sort((a, b) => Math.random());
  });

But it is still sorting them alphabetically (no dates are available).

Thanks, Scott

pdehaan commented 4 years ago

Math.random() returns a float between 0.0 and 1.0, so it probably won’t affect the default sort order. You could try something like subtracting 0.5 so you get a number between -0.5 and +0.5, per https://javascript.info/task/shuffle (click “solution” button).

Or, if you’re using nunjucks and want a single random element from an array/collection there is a random filter.

scottwater commented 4 years ago

That did the trick. Thanks for the tip and explanation.