Skip to content

Instantly share code, notes, and snippets.

@sarunw
Forked from danfascia/11ty_contains.js
Created July 27, 2019 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sarunw/98de04b5487338d7cae21d8ec4a23ab7 to your computer and use it in GitHub Desktop.
Save sarunw/98de04b5487338d7cae21d8ec4a23ab7 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/)
/**
* 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);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment