Last active
February 9, 2023 22:19
-
-
Save danfascia/e15b8e900a767c1b9677d1cbc74cc51c to your computer and use it in GitHub Desktop.
11ty filter to filter a collection (array) by key:value pair - used to filter on custom taxonomies other than tags (source: https://paulrobertlloyd.com/)
This file contains hidden or 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
/** | |
* Select objects in array whose key includes a value | |
* | |
* @param {Array} arr Array to test | |
* @param {String} key Key to inspect | |
* @param {String} value Value key needs to include | |
* @return {String} Filtered array | |
* | |
*/ | |
module.exports = function (arr, key, value) { | |
return arr.filter(item => { | |
const keys = key.split('.'); | |
const reduce = keys.reduce((object, key) => { | |
return object[key]; | |
}, item); | |
const str = String(reduce); | |
return (str.includes(value) ? item : false); | |
}); | |
}; |
@danfascia, thanks for this.
@shanerobinson if you've included it your config then you can use it like this {% for item in list | contains('featured', true) %>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is there an example repo of how to incorporate this into an 11ty project? I'm trying to create multiple custom taxonomies (categories, mediums, etc.) and have spent many hours trying to figure out how to incorporate this with no luck. Thanks in advance for any assistance!