javascripteleventy

Eleventy tags - convert to lowercase and sort alphabetically?


I am using the tag filters from eleventy-base-blog:

eleventyConfig.addFilter("getAllTags", collection => {
  let tagSet = new Set();
  for(let item of collection) {
    (item.data.tags || []).forEach(tag => tagSet.add(tag));
  }
  return Array.from(tagSet);
});

eleventyConfig.addFilter("filterTagList", function filterTagList(tags) {
  return (tags || []).filter(tag => ["all", "no-show"].indexOf(tag) === -1);
});

These work as expected. However, I would like to:

  1. Transform tags to lowercase to minimize Output Conflict from tags like JavaScript, Javascript, and javascript.
  2. Sort tags alphabetically for usability.

I stink at JS and after hours of trying, I must admit defeat. Any help would be much appreciated :)


Solution

  • So there are two points where you could make some adjustments.

    First, when adding a tag to the set, you can covert to lowercase so that they are unique in the set

    tagSet.add(tag.toLowerCase())
    

    and when converting to an array and returning the tags, you can sort them

    Array.from(tagSet).sort();
    

    eleventyConfig.addFilter("getAllTags", collection => {
      let tagSet = new Set();
      for(let item of collection) {
        (item.data.tags || []).forEach(tag => tagSet.add(tag.toLowerCase()));
      }
      return Array.from(tagSet).sort();
    });