Last active
November 18, 2019 17:12
-
-
Save jeromecoupe/f5870b13888b51219a2fb5ad0a23b00a to your computer and use it in GitHub Desktop.
Sort post by categories with 11ty data files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The in a cases.njk template