Explorer
JavaScript

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

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (create a new empty object).
  3. Implement Logic: Handle state and transformations efficiently (iterate over the keys array and copy matching properties).
  4. 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.

Pick Properties from Object

Medium

Write a function pick(obj, keys) that returns a new object with only the specified keys.

Example Scenarios
1Example 1
Input: obj = { a: 1, b: 2, c: 3 }, keys = ["a", "c"]
Output: { a: 1, c: 3 }
Explanation:

Only specified keys are preserved.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
{"a":1,"c":3}