Explorer
JavaScript

Write a function `groupBy(arr, key)` that groups an array of objects by the value of the given key.

Problem Statement

<p>Write a function <code>groupBy(arr, key)</code> that groups an array of objects by the value of the given key.</p>

Examples

Input: arr = [{ cat: "A", val: 1 }, { cat: "B", val: 2 }, { cat: "A", val: 3 }], key = "cat"

Output: { A: [{...}, {...}], B: [{...}] }

Explanation: Grouped by category key.

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: Use reduce to build a grouped object. šŸ’” Hint 2: For each item, use item[key] as the group name. šŸ’” Hint 3: Initialize the group as an empty array if it does not exist, then push the item.

Editorial & Approach

Problem Overview & Intuition

To solve Group Array by Property, we consider the execution characteristics of JavaScript engines. Write a function `groupBy(arr, key)` that groups an array of objects by the value of the given key. 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 (use reduce to build a grouped object).
  3. Implement Logic: Handle state and transformations efficiently (for each item, use item[key] as the group name).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function groupBy(arr, key) {
  return arr.reduce((groups, item) => {
    const group = item[key];
    if (!groups[group]) groups[group] = [];
    groups[group].push(item);
    return groups;
  }, {});
}

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.

Group Array by Property

Medium

Write a function groupBy(arr, key) that groups an array of objects by the value of the given key.

Example Scenarios
1Example 1
Input: arr = [{ cat: "A", val: 1 }, { cat: "B", val: 2 }, { cat: "A", val: 3 }], key = "cat"
Output: { A: [{...}, {...}], B: [{...}] }
Explanation:

Grouped by category key.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
{"eng":[{"name":"Alice","dept":"eng"},{"name":"Bob","dept":"eng"}],"hr":[{"name":"Charlie","dept":"hr"}]}