Search code examples
javascriptnode.jseleventy

Sort titles with localCompare


Using Eleventy as static site generator am unable to figure out how to sort titles in certain alphabet (in my case, Latvian, lv). Documentation related sorting

So far script below works for English.

  eleventyConfig.addCollection("postsDescending", (collection) =>
    collection.getFilteredByGlob("src/posts/*.md").sort((a, b) => {
      if (a.data.title > b.data.title) return 1;
      else if (a.data.title < b.data.title) return -1;
      else return 0;
    })
  );

In my take I try the localeCompare, but getting error collection.getFilteredByGlob(...).from is not a function

const alphabet = ['a','ā','b','c','č','d','e','ē','f','g','ģ','h','i','ī','j','k','ķ','l','ļ','m','n','ņ','o','p','r','s','š','t','u','ū','v','z','ž'];
    eleventyConfig.addCollection("postsDescending", function(collection) {
        return collection.getFilteredByGlob("src/posts/*.md").from(alphabet).sort(function(a, b) {
           return a.localeCompare(b, 'lv', { sensitivity: 'base' });
        });
    });

Needless to say am beginner in Javascript ... Any help much appreciated!


Solution

  • Turns out I am able solve this by myself.

      eleventyConfig.addCollection("postsDescending", (collection) =>
        collection.getFilteredByGlob("src/posts/*.md").sort((a, b) => {
    return a.data.title.localeCompare(b.data.title, 'lv', { sensitivity: 'base' });
        })
      );