Write a function `pick(obj, keys)` that returns a new object with only the specified keys.
Problem Statement
<p>Write a function <code>pick(obj, keys)</code> that returns a new object with only the specified keys.</p>
Examples
Input: obj = { a: 1, b: 2, c: 3 }, keys = ["a", "c"]
Output: { a: 1, c: 3 }
Explanation: Only specified keys are preserved.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
š” Hint 1:
Create a new empty object.
š” Hint 2:
Iterate over the keys array and copy matching properties.
š” Hint 3:
keys.forEach(k => { if (k in obj) result[k] = obj[k]; });
Editorial & Approach
Problem Overview & Intuition
To solve Pick Properties from Object, we consider the execution characteristics of JavaScript engines. Write a function `pick(obj, keys)` that returns a new object with only the specified keys. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.
Step-by-Step Approach
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (create a new empty object).
- Implement Logic: Handle state and transformations efficiently (iterate over the keys array and copy matching properties).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function pick(obj, keys) {
const result = {};
keys.forEach(k => { if (k in obj) result[k] = obj[k]; });
return result;
}
Complexity Analysis
Time Complexity
O(N) linear scan over input
Space Complexity
O(1) constant auxiliary space (or O(N) output)
Edge Cases & Corner Traps Handled
- Empty or boundary inputs (empty arrays, strings, zero length).
- Type checks and unexpected values (e.g.
null,undefined, negative numbers). - Closure preservation and memory isolation between separate invocations.