There is a code to remove child or parent elements from a random array that may contain both child and parent elements. For instance:
<html>
<body>
<div id='1'>
<div id='2'>
<div id='3'>
</div>
<div id='4'>
</div>
</div>
</div>
<div id='5'>
<div id='6'>
</div>
</div>
</body>
</html>
arr = document.getElementsByTagName('div')
// arr: [<div#1>,<div#2>, <div#3>, <div#4>, <div#5>, <div#6>]
From this example, how can I extract the children:
// arr: [<div#3>, <div#4><div#6>]
Or extract the parents:
// arr: [<div#1>, <div#5>]
Currently, the code being used is:
function isDescendant(parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}
function filterArray(arr, parent=true){
newArr = [];
arr.forEach((a)=>{
bool = true
if (parent){
arr.forEach((b)=>{
if (isDescendant(a, b)){
bool = false
};
});
}
else{
arr.forEach((b)=>{
if (isDescendant(b, a)){
bool = false
};
});
}
if(bool){
newArr.push(a)
}
});
return newArr
};
Is there a more efficient solution available?