So here is a very crude code to achieve what you want to achieve. It can be improved of course, but I think functionally this should work ->
start: function() {
var arr = [
{
id: "1",
parentId: "0",
},
{
id: "2",
parentId: "0",
},
{
id: "3",
parentId: "1",
},
{
id: "4",
parentId: "2",
},
];
var out = [];
var input = "2";
var finalOut = [];
this.getParentArray(arr, input, out);
console.log("out", out);
this.getChildArray(arr, input, out, finalOut);
console.log("finalOut", finalOut);
}
/**
* Get parents of the input
*/
getParentArray: function(flatArray = [], input, output = []) {
// Find the node
let node = flatArray.find((f) => f.id == input);
if (node) {
output.unshift(node.id);
// Find parent of the node
let parentNode = flatArray.find((f) => f.id == node.parentId);
if (parentNode) {
// If parent node has further parents, do recursion to get all parents
if (flatArray.findIndex((f) => f.id == parentNode.parentId) != -1) {
this.getParentArray(flatArray, parentNode.id, output);
} else {
// Add parent and it's parent id to the output
output.unshift(parentNode.id);
output.unshift(parentNode.parentId);
}
} else {
// If no parent, add the node parent id on top
output.unshift(node.parentId);
}
} else if (flatArray.findIndex((f) => f.parentId == input) != -1) {
// If no node found and the input exists as parent id to some element, then add this input in the last
output.push(input);
}
}
/**
* Get children of the array
*/
getChildArray: function(flatArray = [], input, output = [], finalOutput = []) {
// Get all children of the input
let children = flatArray.filter((f) => f.parentId == input);
// Create a middle point to hold the data
let midOutput = JSON.parse(JSON.stringify(output));
if (!children || children.length == 0) {
// If no children, just push the output to final output
finalOutput.push(output);
return;
}
children.forEach((child, index) => {
midOutput = JSON.parse(JSON.stringify(output));
if (child) {
midOutput.push(child.id);
// Recursion if child has more children
if (flatArray.findIndex((f) => f.parentId == child.id) != -1) {
this.getChildArray(flatArray, child.id, midOutput, finalOutput);
} else {
finalOutput.push(JSON.parse(JSON.stringify(midOutput)));
}
}
});
}