I am creating a nested list from an array generated from an hierarchical table of categories, with subcategories having a parent ID of the parent category ID. I am trying to display the list in a format like folders and files, where list items with more items in them are grouped together like folders followed by those that don't, let's call them files.
I have managed to create the list but each set of categories and subcategories are displaying in alphabetical order as opposed to the desired format outlined below. I have tried to achieve the desired format inside the recursive function as well as a separate function targeting these "folders" after the list has been generated.
The desired outcome would look like this:
<ul id='myList' class="folder">
<li data-id=0>
<ul class="folder">
<li data-id=1>catA
<ul class="folder">
<li data-id=3>catA_1
<ul>
<li data-id=4>catA_1_1</li>
</ul>
<ul>
<li data-id=5>catA_1_2</li>
</ul>
<ul>
<li data-id=6>catA_1_3</li>
</ul>
</li>
</ul>
<ul class="folder">
<li data-id=8>catA_3
<ul>
<li data-id=9>catA_3_1</li>
</ul>
<ul>
<li data-id=10>catA_3_2</li>
</ul>
<ul class="folder">
<li data-id=11>catA_3_3
<ul>
<li data-id=12>catA_3_3_1</li>
</ul>
<ul data-id=13>catA_3_3_2</ul>
</li>
</ul>
</li>
</ul>
<ul>
<li data-id=7>catA_2</li> <!-- *Note these two (data-id = 7 & 14) trail the above "folders" as they have no items in them -->
</ul>
<ul>
<li data-id=14>catA_4</li>
</ul>
</li>
</ul>
<ul>
<li data-id=2>catB</li> <!-- And so on with catB -->
</ul>
</li>
</ul>
const src = [[1,"catA",0],[2,"catB",0],[3,"catA_1",1],[4,"catA_1_1",3],[5,"catA_1_2",3],[6,"catA_1_3",3],[7,"catA_2",1],[8,"catA_3",1],[9,"catA_3_1",8],[10,"catA_3_2",8],[11,"catA_3_3",8],[12,"catA_3_3_1",11],[13,"catA_3_3_2",11],[14,"catA_4",1],[15,"catB_1",2],[16,"catB_1_1",15],[17,"catB_1_2",16],[18,"catB_1_3",16],[19,"catB_2",15],[20,"catB_3",15],[21,"catB_3_1",20],[22,"catB_3_2",20],[23,"catB_3_3",20],[24,"catB_3_3_1",23],[25,"catB_3_3_2",23],[26,"catB_4",15]];
function tree(src, parent = 0) {
const el = document.getElementById("myList").querySelector("li[data-id='" + parent + "']");
if (!el) return;
for (var i = 0; i < src.length; i++) {
if (src[i][2] === parent) {
const new_parent = src[i][0];
el.insertAdjacentHTML("beforeend", "<ul><li data-id='" + new_parent + "'>" + src[i][1] + "</li></ul>");
el.parentElement.classList.add("folder");
tree(src, new_parent);
}
}
}
tree(src)
<ul id='myList'>
<li data-id=0></li>
</ul>
EDIT: To clarify, the commmented li with data-id=7, (catA_2) is currently being placed alphabetically between two ".folder" ul's instead of after the ".folder" ul's
px(referring to the part of the code that callspx.tree(....)?No, that function is ordering alphabetically- doesn't seem to be alphabetical order, seems reverse alphabetical order"beforeend"instead of"afterend"maybe?