Skip to content

Instantly share code, notes, and snippets.

@isaacrankin
Created October 23, 2015 23:38
Show Gist options
  • Save isaacrankin/01b1a6118d917cfce648 to your computer and use it in GitHub Desktop.
Save isaacrankin/01b1a6118d917cfce648 to your computer and use it in GitHub Desktop.
Flatten a nested array and combine/crawl by a specified property
/**
* Flatten a nested array and combine/crawl by specified property
*/
flattenByProp (arr, prop) {
var flatten = function (arr) {
return arr.reduce(function (flat, toFlatten) {
// combine items on this level
var combo = flat.concat(toFlatten);
// if categories are array,
if(Array.isArray(toFlatten[prop])){
return combo.concat(flatten(toFlatten[prop]));
}else{
return combo;
}
}, []);
};
return flatten(arr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment