SO - 16228467
by Arun P Johny
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
JavaScript
var catalog = [{
category : "a1",
children : [{
category : "a2",
children : []
}, {
category : "b2",
children : [{
category : "a3",
children : []
}, {
category : "b3",
children : []
}]
}, {
category : "c2",
children : []
}]
}, {
category : "b1",
children : []
}, {
category : "c1",
children : [{
category : "d2",
children : [{
category : "c3",
children : []
}, {
category : "d3",
children : [{
category : "a4",
children : []
}, {
category : "b4",
children : []
}, {
category : "c4",
children : []
}, {
category : "d4",
children : []
}]
}]
}, {
category : "e2",
children : [{
category : "e3",
children : []
}]
}]
}];
// console.log(catalog);
// Start function
function findCategory(categoryName) {
var trail = [];
var found = false;
function recurse(categoryAry) {
for (var i = 0; i < categoryAry.length; i++) {
trail.push(categoryAry[i].category);
// Found the category!
if ((categoryAry[i].category === categoryName)) {
found = true;
break;
// Did not match...
} else {
// Are there children / sub-categories? YES
if (categoryAry[i].children.length > 0) {
recurse(categoryAry[i].children);
if(found){
break;
}
}
}
trail.pop();
}
}
recurse(catalog);
return trail
}
function test(str){
...