Hi stuck at one point I have two set of arrays (topicsList & hierarchyList)
let topicsList = [{
"topicId": 1,
"topicName": "Introduction",
},
{
"topicId": 2,
"topicName": "How to Guide",
},
{
"topicId": 3,
"topicName": "Support",
},
{
"topicId": 6,
"topicName": "Lamborghini",
},
{
"topicId": 7,
"topicName": "Mercedes Benz",
},
{
"topicId": 10,
"topicName": "Skoda",
}
]
let hierarchyList = [{
"topicId": 1,
"topicName": "Introduction",
},
{
"topicId": 2,
"topicName": "How to Guide",
"children": [{
"topicId": 6,
"topicName": "Lamborghini",
"children": [{
"topicId": 10,
"topicName": "Skoda",
}]
}]
},
{
"topicId": 3,
"topicName": "Support"
}
]
topicIds = new Set(hierarchyList.map(({ topicId }) => topicId));
topicsList = topicsList.filter(({ topicId }) => !topicIds.has(topicId));
console.log(topicsList);
I am filtering out the TopicsList
based on the topicId present in hierarchyList
, but hierarchyList now also has this nested childrens and it can be n levels deep
I also need to check now if this topicId is also present in nested childrens array if it does I need to do the same filter it out from Topic List. I’m not sure how can i achieve this behaviour
Expected O/P
TopicList = [{
"topicId": 7,
"topicName": "Mercedes Benz",
}]
2
Answers
just use a set and then map with this simple function which you then filter
You can use
.flatMap()
on yourhierarchyList
. For each object, you can extract itstopicId
like you do currently, but also itschildren
array (defaulting it to an empty array if it doesn’t exist via destructuring). You can then recursively call.flatMap()
on the children, spreading the results of the recursive calls into the mapped array. Once you’ve built the array of ids, you can pass it to your Set for quick lookup and deduplication as you do currently: