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));

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));
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.