'How to filter a four dimensional array in Javascript
I have the following array:
[
{
"type": "great-grandparent",
"value": "senior one",
"grandparents": [
{
"value": "special grandparent",
"parents": [
{
"value": "special parent",
"children": [
{
"value": "special child 1"
},
{
"value": "special child 2"
}
]
},
{
"value": "special parent 256",
"children": []
}
]
},
{
"value": "special grandparent 2",
"parents": [
{
"value": "happy parent",
"children": [
{
"value": "fluffy child 1"
},
{
"value": "chilled child 2"
}
]
},
{
"value": "special parent 242",
"children": []
}
]
}
]
},
{
"type": "great-grandparent 2",
"value": "the other senior one",
"grandparents": [
{
"value": "special grandparent 2",
"parents": [
{
"value": "special parent 2",
"children": [
{
"value": "peculiar child 1"
},
{
"value": "curious child 2"
}
]
},
{
"value": "special parent 3",
"children": []
}
]
},
{
"value": "special grandparent 3",
"parents": [
{
"value": "happy parent",
"children": [
{
"value": "fast child 1"
},
{
"value": "talkative child 2"
}
]
},
{
"value": "special parent 4",
"children": []
}
]
}
]
},
{
"type": "great-grandparent 3",
"value": "the other slightly senior one",
"grandparents": [
{
"value": "special grandparent 67",
"parents": [
{
"value": "special parent 243",
"children": []
},
{
"value": "special parent 34554",
"children": []
}
]
},
{
"value": "special grandparent 345",
"parents": [
{
"value": "extremely happy parent"
},
{
"value": "special parent 454",
"children": []
}
]
}
]
}
]
I am trying to return a nested array of great-grandparent (containing grandparent, parent and child arrays/objects) objects where children is not an empty array.
So given the above array, I expect an array of 2 elements to be returned with special parent 256, 242, 3, and 4 omitted as they have zero children. The last great-grandparent object has zero children so this great-grandparent object should be completely omitted too
So far I have:
const filtered = greatGrandparents
.filter((greatGrandparentObj) => greatGrandparentObj.grandparents
.filter((grandparentObj) => grandparentObj.parents
.filter((parentObj) => parentObj.children.length !== 0).length).length)
I am getting the expected greatGrandparent objects back but I am also getting back parents with zero children, I want these to be omitted.
Appreciate any guidance
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
