I have an array which looks like this:
var arrayElements=
[
["1","description 1",
[
["1.1","description 1.1"],
["1.2","description 1.2"],
["1.2","description 1.3"]
]
]
,
["2","description 2"],
["3","description 3",
[
["3.1","description 3.1"],
["3.2","description 3.2",
[
["3.2.1","description 3.2.1"],
["3.2.2","description 3.2.2"],
["3.2.2","description 3.2.3"]
]
],
["3.3","description 3.3"]
]
],
["4","description 4"]
];
I want to loop trough the following array, be able to access all values as well as print depth of each element. Expected outcome in console would be something like this:
description 1, depth 1
description 1.1, depth 2
description 1.2, depth 2
description 1.3, depth 2
description 2, depth 1
description 3, depth 1
description 3.1, depth 2
description 3.2, depth 2
description 3.2.1, depth 3
description 3.2.2, depth 3
description 3.2.3, depth 3
description 3.3, depth 2
description 4, depth 1
Here's what I have tried:
var depth = 0;
function listNodes(array){
for(i = 0; i < array.length;i++){
if( /* itearating over root array */ ){
depth = 1;
}
if(array[i][2] instanceof Array){
depth++;
console.log(array[i][1] + " depth: "+depth);
listNodes(array[i][2]);
}else{
console.log(array[i][1] + " depth: "+depth);
}
}
}
listNodes(arrayElements);
I'm unable to loop through this array, it gets stuck even though it should continue. Another problem is the fact that my variable storing depth is not working as I'm unable to determine when the loop iterates over the root array so that I can reset the depth
counter. Any ideas?