0

Hi, I have created a function that searches for a category in a category tree object and returns all the paths for it as an array of strings, please advice how I can improve it ?
the result im getting now is :
["vehicles",["cars","mercedes"],["trucks","mercedes"],["motorcycles","BMW"]]
i need it in one dimesional array like this :
["vehicles","cars","mercedes","trucks","mercedes","motorcycles","BMW"]

here is also a plunker url for the same code im trying t solve :
Click Here
thanks in advance,
please advice.

var categories = {category:"vehicles",children:[
                 {category:"cars",children:[{category:"mercedes",children:[]}]},
                 {category:"trucks",children:[{category:"mercedes",children:[]}]},
                 {category:"motorcycles",children:[{category:"BMW",children:[]}]}
]};

function getnodes(nodes)
{
 var arr=[];
  if (!nodes.children.length) return nodes.category;
  else{
    arr.push(nodes.category);
  for(var i =0 ; i<nodes.children.length ; i++){
      arr.push(getnodes(nodes.children[i]));
  }
  }
     return arr;
}

 var allnodes = getnodes(categories);
 console.log(JSON.stringify(allnodes));
1
Contributor
1
Reply
13
Views
2 Months
Discussion Span
Last Post by samertaha
0

i have solved it :

var categories = {category:"vehicles",children:[
                 {category:"cars",children:[{category:"mercedes",children:[]}]},
                 {category:"trucks",children:[{category:"mercedes",children:[]}]},
                 {category:"motorcycles",children:[{category:"BMW",children:[]}]}
]};

function getnodes(nodes)
{
 var arr=[];
  if (!nodes.children.length) return nodes.category;
  else{
    arr=arr.concat(nodes.category);
  for(var i =0 ; i<nodes.children.length ; i++){
      arr=arr.concat(getnodes(nodes.children[i]));
  }
  }
  arr = arr.filter (function (value, index, array) { 
    return array.indexOf (value) == index;
});
     return arr;
}

 var allnodes = getnodes(categories);
 console.log(JSON.stringify(allnodes));
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.