I ran into a problem that I don’t know how to correctly compose a recursive function. the logic is such that if you delete an item in the application, then all items whose parentId is equal to the id of the item that decided to delete are deleted, and so on. I hope I explained well, I will be very grateful for the help!
const arr = [
{title: 'one', id: 1, parentId: null},
{title: 'two', id: 2, parentId: 1},
{title: 'three', id: 3, parentId: null},
{title: 'four', id: 4, parentId: 2},
{title: 'five', id: 5, parentId: 2},
{title: 'six', id: 6, parentId: 5},
{title: 'seven', id: 7, parentId: 3},
]
// if we decide to remove "one", the result will be
[
{title: 'three', id: 3, parentId: null},
{title: 'seven', id: 7, parentId: 3},
]
I'm stuck on a version that removes subtasks with only one parentId level
const deleteFunc = (array, value) => {
array = array.filter(item => item.id !== value);
const findSubTask = array.filter((item) => item.parentId === value);
array = array.filter(item => item.id !== findSubTask[0].id);
const findSecondSubTask = array.find(
(key) => key.parentId === findSubTask[0].id,
);
if (findSecondSubTask) {
return deleteFunc(array, findSubTask[0].id);
}
return array;
};
console.log(deleteFunc(arr, 1));
1, you delete2because its parent is 1, you delete4and5because their parents are2, you delete5because its parent is2, and you delete6because its parent is5. The ones that are left are3and7. @otejiri