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
What counts as falsy? Any value where
โข
Important: Arrays are treated as objects where indices are keys. The input is guaranteed to be valid JSON (output of
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, NaNImportant: 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
objis a valid JSON object (output ofJSON.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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code