#2823
Medium JavaScript Deep object filter
56.7% acceptance
Mar 31, 2026
17
3
Given an object or an array obj and a function fn, return a filtered object or array filteredObject.
Function deepFilter should perform a deep filter operation on the obj. The deep filter operation should remove properties for which the output of the filter function fn is false, as well as any empty objects or arrays that remain after the keys have been removed.
If the deep filter operation results in an empty object or array, with no remaining properties, deepFilter should return undefined to indicate that there is no valid data left in the filteredObject.
Solution
TypeScript
Time O(2^n)
Space O(n)
type JSONValue =
| null
| boolean
| number
| string
| JSONValue[]
| { [key: string]: JSONValue };
type Obj = Record<string, JSONValue> | Array<JSONValue>;
function deepFilter(obj: Obj, fn: Function): Obj | undefined {
function helper(val: JSONValue): JSONValue | undefined {
if (Array.isArray(val)) {
const filtered = val
.map(helper)
.filter((v) => v !== undefined) as JSONValue[];
return filtered.length > 0 ? filtered : undefined;
} else if (val !== null && typeof val === "object") {
const result: Record<string, JSONValue> = {};
let hasKeys = false;
for (const key in val) {
const res = helper(val[key]);
if (res !== undefined) {
result[key] = res;
hasKeys = true;
}
}
return hasKeys ? result : undefined;
} else {
return fn(val) ? val : undefined;
}
}
return helper(obj) as Obj | undefined;
}