Every parent element should contain total count of all subcategories. It will be very good if solution will be using only Array object methods and no using of while loops.
This is the example of base structure:
const base = [
{ id: 1, count: 2, parentId: null },
{ id: 2, count: 4, parentId: 1 },
{ id: 3, count: 0, parentId: 2 },
{ id: 6, count: 8, parentId: 3 },
{ id: 7, count: 8, parentId: 3 },
{ id: 8, count: 2, parentId: 7 },
{ id: 4, count: 2, parentId: null },
{ id: 5, count: 1, parentId: 4 },
];
This is how it should be looking like:
const expected = [
{ id: 1, count: 2, total: 24, parentId: null },
{ id: 2, count: 4, total: 22, parentId: 1 },
{ id: 3, count: 0, total: 18, parentId: 2 },
{ id: 6, count: 8, total: 8, parentId: 3 },
{ id: 7, count: 8, total: 10, parentId: 3 },
{ id: 8, count: 2, total: 2, parentId: 7 },
{ id: 4, count: 2, total: 3, parentId: null },
{ id: 5, count: 1, total: 1, parentId: 4 },
];
Here's my current code. I think here somehow I need go to the last level
and then starting from last item to top concataning prev level with current
level count prop value that is why I made named IIFE.
let c = a.map(cat => {
const top = a.filter(v => cat.id === v.parentId);
let test;
return ({
...cat,
total: (test = categs => {
return categs.reduce((acc, val) => {
/* ??? */
return acc + val.count
}, cat.count);
})(top)
})
})