If I were to have an array of objects containing hierarchical data:
const data = [
{ groupId: 1, parentGroupId: null },
{ groupId: 2, parentGroupId: 1 },
{ groupId: 3, parentGroupId: 1 },
{ groupId: 4, parentGroupId: null },
{ groupId: 5, parentGroupId: 99 },
{ groupId: 6, parentGroupId: 2 },
{ groupId: 7, parentGroupId: 6 },
{ groupId: 8, parentGroupId: 4 }];
How can a recursive TypeScript function be implemented that takes a parentGroupId parameter and returns an array of groupId's that includes the parent groupId and all its descendants, grandchildren, great-grandchildren, and so on recursively.
For example, the function should output:
[1,2,3,6,7]
Currently, a function exists that returns the parent and its immediate children, but the recursive aspect to include grandchildren, great-grandchildren, etc. is missing.
const data = [
{ groupId: 1, parentGroupId: null },
{ groupId: 2, parentGroupId: 1 },
{ groupId: 3, parentGroupId: 1 },
{ groupId: 4, parentGroupId: null },
{ groupId: 5, parentGroupId: 99 },
{ groupId: 6, parentGroupId: 2 },
{ groupId: 7, parentGroupId: 6 },
{ groupId: 8, parentGroupId: 4 }];
function getChildIds(arr, parentGroupId) {
return arr.reduce(function (ret, item) {
if (item.parentGroupId == parentGroupId || item.groupId == parentGroupId) {
ret = ret.concat(item.groupId);
}
return ret;
}, []);
}
console.log(getChildIds(data, 1));