Compact Object - Problem
Compact Object Challenge

Imagine you have a messy JSON object or array filled with unnecessary falsy values that are cluttering your data structure. Your mission is to clean it up by creating a compact version!

Given an object or array obj, return a compact object where all keys containing falsy values have been removed. This cleaning process should work recursively on nested objects and arrays too.

What counts as falsy? Any value where Boolean(value) returns false:
โ€ข false, 0, -0, 0n, "", null, undefined, NaN

Important: Arrays are treated as objects where indices are keys. The input is guaranteed to be valid JSON (output of JSON.parse).

Input & Output

example_1.py โ€” Basic Object Cleaning
$ Input: {"a": null, "b": ["x", 0, false, 1], "c": {"d": "", "e": "hello"}}
โ€บ Output: {"b": ["x", 1], "c": {"e": "hello"}}
๐Ÿ’ก Note: Removes 'a' (null), filters array 'b' to remove 0 and false, removes 'd' from nested object 'c' due to empty string
example_2.py โ€” Array Compaction
$ Input: [null, 0, 5, "", true, false, NaN]
โ€บ Output: [5, true]
๐Ÿ’ก Note: Keeps only truthy values: 5 and true. Removes null, 0, empty string, false, and NaN
example_3.py โ€” Nested Structure Edge Case
$ Input: {"a": {"b": null}, "c": [0, false, ""], "d": {}}
โ€บ Output: {}
๐Ÿ’ก Note: All nested structures become empty after cleaning, so the entire object becomes empty. Object 'a' becomes {}, array 'c' becomes [], and 'd' is already {}

Constraints

  • The input obj is a valid JSON object (output of JSON.parse)
  • Object keys are always strings
  • Values can be: objects, arrays, strings, numbers, booleans, or null
  • Maximum nesting depth: 100 levels
  • Maximum number of properties: 104

Visualization

Tap to expand
BEFORE: Messy CabinetDrawer 1: Empty folders โŒDrawer 2: Has sub-drawers ๐Ÿ“null docsgood filesDrawer 3: Corrupted data โŒ๐Ÿงน CleanAFTER: Clean CabinetDrawer 2: Clean sub-drawer ๐Ÿ“good files โœ…โœจ Only useful content remains!
Understanding the Visualization
1
Start at Top Level
Begin examining the main filing cabinet
2
Open Each Drawer
For each drawer (object key/array index), examine contents
3
Recursive Deep Clean
If drawer contains sub-drawers, clean those first
4
Remove Junk
Discard empty folders, blank documents, corrupted files
5
Final Assembly
Keep only useful items in a clean, organized structure
Key Takeaway
๐ŸŽฏ Key Insight: Recursive cleaning ensures that even deeply nested structures are properly compacted, and empty containers created during the process are removed for a truly clean result.
Asked in
Google 42 Microsoft 38 Amazon 35 Meta 28
89.4K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen