Skip to content

Instantly share code, notes, and snippets.

@simenbrekken
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save simenbrekken/a876259c6c1c29de568d to your computer and use it in GitHub Desktop.

Select an option

Save simenbrekken/a876259c6c1c29de568d to your computer and use it in GitHub Desktop.
Find ancestors by parent traversal
var lodash = require('lodash')
var getAncestors = function(node, nodes) {
var ancestors = []
var ancestor = node
while (ancestor) {
ancestors.unshift(ancestor)
ancestor = lodash.find(nodes, {id: ancestor.parent})
}
return ancestors
}
var ancestors = getAncestors([
{id: 1, parent: null},
{id: 2, parent: 1},
{id: 3, parent: 1},
{id: 4, parent: 3}
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment