-
-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Total Headcount #5
Comments
I think getting the counts from backend is best, but you can try to count children recursively. function computeChildrenCount(categories) {
// Map to store children for each category
const childrenMap = {};
// Initialize children count
categories.forEach(category => {
childrenMap[category.id] = [];
});
// Build children relationships
categories.forEach(category => {
if (category.parent_id !== null) {
childrenMap[category.parent_id].push(category.id);
}
});
// Function to recursively count children
function countChildren(id) {
return childrenMap[id].reduce(
(count, childId) => count + 1 + countChildren(childId),
0
);
}
// Add total_children to each category
return categories.map(category => ({
...category,
total_children: countChildren(category.id)
}));
}
const categories = [
{ id: 1, name: "Electronics", parent_id: null },
{ id: 2, name: "Phones", parent_id: 1 },
{ id: 3, name: "Laptops", parent_id: 1 },
{ id: 4, name: "Smartphones", parent_id: 2 },
{ id: 5, name: "Gaming Laptops", parent_id: 3 },
{ id: 6, name: "Accessories", parent_id: 1 },
{ id: 7, name: "Chargers", parent_id: 6 }
];
const result = computeChildrenCount(categories);
console.log(result); And the output will be:
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wanted to see if it’s possible to get a total headcount of a node. This headcount would include both direct and indirect reports. Direct reports are currently accounted for as children, but I’m unsure how to account for indirect reports, such as children of children (which could be infinite).
The text was updated successfully, but these errors were encountered: