Looking for a Solution: Is there an efficient method to filter out objects from an array based on a specific property value without using recursion?
The Issue: While the recursive approach works for filtering, it struggles with performance due to a large dataset and numerous nested objects within each object.
Here is a snippet of sample data:
[{
children: [{
children: [{
children: [],
isWorking: 'yes'
}]
}]
}, {
children: [],
isWorking: 'no'
}, {
children: [{
children: [{
children: [],
isWorking: 'no'
}]
}]
}, {
children: [{
children: [],
isWorking: 'yes'
}]
}, ...]
- I want to filter out the top-level objects that have a nested
isWorking
property set toyes
. - The
isWorking
property is only present in objects without any children. i.e.children: []
While I have achieved this using recursion, I am seeking a more optimized solution to enhance performance.
This is my current working solution:
const parent = [{
children: [{
children: [{
children: [],
isWorking: 'yes'
}]
}]
}, {
children: [],
isWorking: 'no'
}, {
children: [{
children: [{
children: [],
isWorking: 'no'
}]
}]
}, {
children: [{
children: [],
isWorking: 'yes'
}]
}];
const isWorkingFlagArr = [];
function checkForOccupation(arr) {
arr.forEach(obj => {
(!obj.children.length) ? isWorkingFlagArr.push(obj.isWorking === 'yes') : checkForOccupation(obj.children)
})
}
checkForOccupation(parent);
const res = parent.filter((obj, index) => isWorkingFlagArr[index]);
console.log(res);