Magicsheet logo

Compact Object

Medium
12.5%
Updated 8/1/2025

Asked by 1 Company

Topics

Compact Object

What is this problem about?

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

Why is this asked in interviews?

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.

Algorithmic pattern used

The problem is solved using Recursive Traversal.

  1. Base Case: If the value is not an object or is null, return it.
  2. Array Case: If the value is an array, iterate through it, recursively call the function on each element, and only keep the "truthy" results in a new array.
  3. Object Case: If the value is an object, iterate through its keys, recursively compact each value, and only add the key-value pair to a new object if the compacted value is truthy.

Example explanation

Input: {"a": 1, "b": [null, 0, 5], "c": {"d": false, "e": "hello"}}

  1. Process a: 1. 1 is truthy. Keep.
  2. Process b. It's an array.
    • null is falsy. Remove.
    • 0 is falsy. Remove.
    • 5 is truthy. Keep. New b is [5].
  3. Process 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"}}

Common mistakes candidates make

  • Shallow Compact: Only removing top-level falsy values and ignoring nested ones.
  • Type Checking: Confusing typeof [] === 'object' (which is true) and not distinguishing between arrays and plain objects.
  • Modifying Originals: Attempting to delete keys in-place, which can lead to issues during iteration. It's safer to build a new object/array.

Interview preparation tip

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.

Similar Questions