Skip to content

Instantly share code, notes, and snippets.

@justinobney
Created November 14, 2014 17:30
Show Gist options
  • Select an option

  • Save justinobney/4c96c6cfddd4c9cfe3f8 to your computer and use it in GitHub Desktop.

Select an option

Save justinobney/4c96c6cfddd4c9cfe3f8 to your computer and use it in GitHub Desktop.
var data = [{
id: 1,
children: [{
id: 2,
children: [{
id: 3,
children: [{
id: 4,
children: []
}]
}]
}]
}, {
id: 5,
children: [{
id: 6,
children: [{
id: 7,
children: []
}]
}]
}, {
id: 8,
children: [{
id: 9,
children: [{
id: 10,
children: []
}]
}]
}];
function getRecurse() {
var path = [];
var found = false;
return recurse;
function recurse(collection, target) {
collection.forEach(function(item) {
if (target == item.id){
found = true;
path.push(item.id);
}
if (item.children.length) {
if(!found){
path.push(item.id)
recurse(item.children, target)
}
if(!found)
path.pop();
}
});
return path;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment