We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Compact Object

Difficulty: Medium


Problem 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.

Key Insights

  • The problem requires filtering out falsy values from an object and its nested structures.
  • Objects can contain arrays, and arrays can contain other objects or arrays, necessitating a recursive approach.
  • Falsy values in JavaScript include null, 0, false, "", undefined, and NaN.

Space and Time Complexity

Time Complexity: O(n), where n is the total number of keys/values in the object or array.
Space Complexity: O(n), as we may need to create a new object or array that could potentially hold all non-falsy values.

Solution

The solution involves a recursive function that iterates through each key-value pair in the object or array. If the value is an array or an object, the function is called recursively to process that value. Falsy values are filtered out during this process, and only non-falsy values are returned. The final result is constructed by including keys with non-falsy values.

Code Solutions

def compact_object(obj):
    if isinstance(obj, dict):
        return {k: compact_object(v) for k, v in obj.items() if v or isinstance(v, (list, dict))}
    elif isinstance(obj, list):
        return [compact_object(v) for v in obj if v or isinstance(v, (list, dict))]
    return obj

# Example usage
print(compact_object([null, 0, false, 1]))  # Output: [1]
print(compact_object({"a": null, "b": [false, 1]}))  # Output: {"b": [1]}
← Back to All Questions