2705. Compact Object
Description
Given an object or array obj, return a compact object.
A compact object is the same as the original object, except with keys containing falsy values removed. This operation applies to the object and any nested objects. Arrays are considered objects where the indices are keys. A value is considered falsy when Boolean(value) returns false.
You may assume the obj is the output of JSON.parse. In other words, it is valid JSON.
Example 1:
Input: obj = [null, 0, false, 1] Output: [1] Explanation: All falsy values have been removed from the array.
Example 2:
Input: obj = {"a": null, "b": [false, 1]}
Output: {"b": [1]}
Explanation: obj["a"] and obj["b"][0] had falsy values and were removed. Example 3:
Input: obj = [null, 0, 5, [0], [false, 16]] Output: [5, [], [16]] Explanation: obj[0], obj[1], obj[3][0], and obj[4][0] were falsy and removed.
Constraints:
objis a valid JSON object2 <= JSON.stringify(obj).length <= 106
Solutions
Solution 1: Recursion
Thinking
Falsy entries must be dropped from both objects and arrays, including nested ones. Serializing first would lose key semantics and blur the array/object distinction.
Non-objects are returned as-is. Arrays filter falsy items then recurse; plain objects keep only truthy values and compact them. Empty objects and arrays are truthy, so they stay, which matches the statement.
If obj is not an object or is null, the function will return it as is, because there's no need to check for keys in non-object values.
If obj is an array, it will use obj.filter(Boolean) to filter out falsy values (like null, undefined, false, 0, ""), then use map(compactObject) to recursively call compactObject on each element. This ensures that nested arrays are also compacted.
If obj is an object, it will create a new empty object compactedObj. It will iterate over all keys of obj, and for each key, it will recursively call compactObject on the corresponding value, then store the result in the value variable. If the value is truthy (i.e., not falsy), it will assign it to the compacted object with the corresponding key.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |