Skip to content

Instantly share code, notes, and snippets.

@jeromecoupe
Last active November 18, 2019 17:12
Show Gist options
  • Save jeromecoupe/f5870b13888b51219a2fb5ad0a23b00a to your computer and use it in GitHub Desktop.
Save jeromecoupe/f5870b13888b51219a2fb5ad0a23b00a to your computer and use it in GitHub Desktop.
Sort post by categories with 11ty data files
const cases = [
{
id: "123456",
title: "This is a case red blue",
categories: [
{ id: "1", slug: "red" },
{ id: "2", slug: "blue" }
]
},
{
id: "23456",
title: "This is another case red blue green",
categories: [
{ id: "1", slug: "red" },
{ id: "2", slug: "blue" }
]
},
{
id: "65478",
title: "This is a case blue",
categories: [{ id: "2", slug: "blue" }]
},
{
id: "65478",
title: "This is a case red green",
categories: [
{ id: "1", slug: "red" },
{ id: "3", slug: "green" }
]
}
];
function getUniqueCategories(cases) {
let categories = [];
cases.forEach(item => {
categories.push(...item.categories);
});
let uniqueCategories = Array.from(
new Set(categories.map(JSON.stringify))
).map(JSON.parse);
return uniqueCategories;
}
function sortCases(cases, categories) {
let sortedCases = [];
categories.forEach(category => {
let filteredCases = cases.filter(item => {
let itemCats = JSON.stringify(item.categories);
let currentCat = JSON.stringify(category);
return itemCats.includes(currentCat);
});
let casesObject = {
...category,
cases: [...filteredCases]
};
sortedCases.push(casesObject);
});
return sortedCases;
}
module.exports = sortCases(cases, getUniqueCategories(cases));
@jeromecoupe
Copy link
Author

jeromecoupe commented Nov 18, 2019

The in a cases.njk template

---
pagination:
    data: cases
    alias: category
    size: 1
permalink: /cases/category/{{ category.slug | slug }}.html
---
{% for post in category.cases %}
    <p>{{ post.title }}</p>
{% endfor %}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment