Given an object and a filter function, write a function that will go through and filter the object, then return a filtered object.
Function:
deepFilter(obj, filter)
Input Object:
const obj = {
a: 1,
b: {
c: 2,
d: -3,
e: {
f: {
g: -4,
},
},
h: {
i: 5,
j: 6,
},
}
}
Callback Function:
const filter = (n) => n >= 0
Output:
{ a: 1, b: { c: 2, h: { i: 5, j: 6 } } }
My implementation:
function deepFilter(obj, filter, resultObj){
if(typeof(obj)!=="object"){
return obj
}
for(let key in obj){
if(obj.hasOwnProperty(key)){
const filteredValue = deepFilter(obj[key], filter, resultObj)
if(filter(filteredValue)){
resultObj[key] = filteredValue;
}
}
}
return resultObj
}
The output isn’t what is expected.
My output:
{ a: 1, c: 2, i: 5, j: 6 }
Is there a different approach to this problem or is it something that I’m missing in the function implementation?
6
Answers
You could treat every nested object as own object and return only an object if the nested value/objects have wanted values.
The problem you forget to collect the child objects containing filtered data. Check whether the child objects have data after filtering and them to the parent object.
I’ve added
K: 0
to the source object to have some falsy value to test with.Some fancy and fast no-braces solution:
More readable:
The main issue is that you are reusing your
resultObj
, so nested objects are getting flattened.I’m also unsure why you’re using
hasOwnProperty
there. I feel like you’re building in a lot of unnecessary checks. All you need is something like this, where you go through each key recursively and add it to the result only if it maches the filter:this is a classic interview question which can be easily solved using recursion.
So basically you need to remove all negative numbers from the object key-value pairs.
You need to write a RECURSIVE
function that will take care of any level of nesting.
Here is an example: