javascript - How to trace all paths of a tree like data structure? -


let's have nested object so:

{   label: 'parent',   eyecolor: 'brown',   kids: [     {       label: 'kid_0',       eyecolor: 'brown',       kids: [         {           label: 'kid_0_0',           eyecolor: 'green',           kids: []         },         {           label: 'kid_0_1',           eyecolor: 'brown',           kids: [             {               label: 'kid_0_1_0',               eyecolor: 'brown',               kids: []             }           ]         }       ],     },     {       label: 'kid_1',       eyecolor: 'brown',       kids: [         {           label: 'kid_1_0',           eyecolor: 'brown',           kids: []         }       ],     },     {       label: 'kid_2',       eyecolor: 'green',       kids: []     }   ] }; 

if wanted store unique paths, how recursively? i've tried many attempts, can't seem obtain unique paths (my paths build on top of previous paths).

so expected output be:

[   ['parent', 'kid_0', 'kid_0_0],   ['parent', 'kid_0', 'kid_0_1, kid_0_1_0],   ['parent', 'kid_1', 'kid_1_0],   ['parent', 'kid_2] ] 

but if wanted stop path when found kid or node eyecolor other brown, path stop there. have change obtain following:

[   ['parent', 'kid_0', 'kid_0_1, kid_0_1_0],   ['parent', 'kid_1', 'kid_1_0], ] 

this current code, error-ing out b/c of maximum call stack.

var printpaths = function(node, color) {   var paths = [];    var trackpath = function(obj, feature, path) {     if (obj.eyecolor === 'brown') {       path.push(node.label);     } else if (obj.eyecolor !== 'brown') {       paths.push(path);     } else if (obj.kids.length === 0) {       paths.push(path);     }      (var = 0; < obj.kids.length; i++) {       trackpath(obj.kids[i], feature, path)       path.pop();     }   };    trackpath(node, color, []);   return paths;  } 

your approach fine, problem assignment or argument passing doesn't copy arrays. introduce slice() call recursion:

function printpaths(node, color) {   var paths = [];    function trackpath(obj, feature, path) {     if (obj.eyecolor !== feature) { // found target       paths.push(path);       return;     } // else continue     path.push(obj.label);      (var = 0; < obj.kids.length; i++) {       trackpath(obj.kids[i], feature, path.slice()); //                                        ^^^^^^^^     }   }    trackpath(node, color, []);   return paths; } 

Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -