The Compact Object interview question involves cleaning up a complex JavaScript object or array by removing all "falsy" values. Falsy values include false, null, 0, "" (empty string), undefined, and NaN. The catch is that this cleanup must be performed recursively—if the object contains nested objects or arrays, those must also be "compacted."
Microsoft asks the Compact Object coding problem to test a candidate's proficiency with recursion and JavaScript's specific type system. It evaluates how well you can handle different data types (Object vs Array vs Primitive) and whether you can write a robust recursive function that doesn't cause a stack overflow or modify the original data incorrectly.
The problem is solved using Recursive Traversal.
Input: {"a": 1, "b": [null, 0, 5], "c": {"d": false, "e": "hello"}}
a: 1. 1 is truthy. Keep.b. It's an array.
null is falsy. Remove.0 is falsy. Remove.5 is truthy. Keep.
New b is [5].c. It's an object.
d: false is falsy. Remove.e: "hello" is truthy. Keep.
New c is {"e": "hello"}.
Output: {"a": 1, "b": [5], "c": {"e": "hello"}}typeof [] === 'object' (which is true) and not distinguishing between arrays and plain objects.In JavaScript, Boolean(value) is a quick way to check if a value is truthy. When writing recursive functions, always consider the maximum nesting depth—though for most interview problems, standard recursion is fine.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Average Height of Buildings in Each Segment | Medium | Solve | |
| Bulb Switcher II | Medium | Solve | |
| Count Paths With the Given XOR Value | Medium | Solve | |
| Count Submatrices With Equal Frequency of X and Y | Medium | Solve | |
| Count Substrings That Differ by One Character | Medium | Solve |