Created
October 23, 2015 23:38
-
-
Save isaacrankin/01b1a6118d917cfce648 to your computer and use it in GitHub Desktop.
Flatten a nested array and combine/crawl by a specified property
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
/** | |
* 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