Last active
August 29, 2015 14:05
-
-
Save simenbrekken/a876259c6c1c29de568d to your computer and use it in GitHub Desktop.
Find ancestors by parent traversal
This file contains hidden or 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
| 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