Explorer
JavaScript

Write a function `omit(obj, keys)` that returns a new object without the specified keys.

Problem Statement

<p>Write a function <code>omit(obj, keys)</code> that returns a new object without the specified keys.</p>

Examples

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

Output: { a: 1, c: 3 }

Explanation: Key "b" is omitted from the result.

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: Create a new object with all properties, then remove the specified keys. šŸ’” Hint 2: Or filter Object.entries() and reconstruct the object. šŸ’” Hint 3: const set = new Set(keys); return Object.fromEntries(Object.entries(obj).filter(([k]) => !set.has(k)));

Editorial & Approach

Problem Overview & Intuition

To solve Omit Properties from Object, we consider the execution characteristics of JavaScript engines. Write a function `omit(obj, keys)` that returns a new object without 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 object with all properties, then remove the specified keys).
  3. Implement Logic: Handle state and transformations efficiently (or filter object.entries() and reconstruct the object).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function omit(obj, keys) {
  const set = new Set(keys);
  return Object.fromEntries(Object.entries(obj).filter(([k]) => !set.has(k)));
}

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.

Omit Properties from Object

Medium

Write a function omit(obj, keys) that returns a new object without the specified keys.

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

Key "b" is omitted from the result.

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