⚡Flashcard Drill➔
NeetCode #967LC-2631MediumJavaScript
← Back to All Problems

#967 · #2631 · Group By(分组)

📌 Problem Statement & Constraints

Implement Array.prototype.groupBy(fn): group the elements by the value returned by fn(element) and return a plain object whose keys are the (stringified) group results and whose values are arrays of the grouped elements.

💡 Core Algorithmic Approaches

  1. Extend Array.prototype with the groupBy method.
  2. Iterate this, compute k = fn(x), and append x to res[k].
  3. Use logical-or assignment res[k] ||= [] to create the bucket on first encounter.
  4. Do not use an arrow function, since this must refer to the calling array.

💻 Benchmark Python3 Implementation

Array.prototype.groupBy = function(fn) {
    const res = {};
    for (const x of this) {
        const k = fn(x);
        (res[k] ||= []).push(x);              // create the bucket on first encounter
    }
    return res;
};

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass over the array.
💾 Space Complexity
O(n): the result object.

⚠️ Interview Pitfalls & Follow-ups

  • Defining the method with an arrow function: this would be lost.
  • Forgetting to initialise res[k]: that throws on undefined.push.
  • Expecting non-string keys to stay distinct: object keys are coerced to strings, so 1 and a string 1 merge into one bucket.
  • Returning a Map: the problem requires a plain object.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related JavaScript Problems