Skip to content

Instantly share code, notes, and snippets.

@crapthings
Created January 11, 2018 04:12
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 crapthings/5b4afdf8094f63d265f604a3d399bb61 to your computer and use it in GitHub Desktop.
Save crapthings/5b4afdf8094f63d265f604a3d399bb61 to your computer and use it in GitHub Desktop.
find children in items by root as array
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