Created
January 11, 2018 04:12
-
-
Save crapthings/5b4afdf8094f63d265f604a3d399bb61 to your computer and use it in GitHub Desktop.
find children in items by root as array
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
module.exports = function findChildren(root, items = [], opts = {}) { | |
const { rootKey, foreignKey, withRoot } = opts | |
const bypass = {} | |
let children = [root] | |
let nextItems = [] | |
recurse() | |
if (!withRoot) | |
children.shift() | |
return children | |
function recurse() { | |
for (child of children) { | |
if (bypass[child[rootKey]]) continue | |
const foundChildren = items.filter(item => child[rootKey] === item[foreignKey]) | |
if (foundChildren.length) { | |
children = children.concat(foundChildren) | |
bypass[child[rootKey]] = true | |
recurse() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment