Group Array Items by Key
Implement groupBy(array, keyFn) that buckets array items into an object keyed by keyFn(item), with each value an array of the items sharing that key. A common warm-up that tests comfort with reduce, object accumulation, and the new ES2024 grouping helpers.
Examples
Input: groupBy([6.1, 4.2, 6.3], Math.floor)
Output: { '4': [4.2], '6': [6.1, 6.3] }
// Each number is bucketed by its floored value (object keys are strings).
Input: groupBy(people, p => p.dept)
Output: { eng: [...], design: [...] }
// Items are grouped by the computed department key.
Constraints
- Each bucket must be an array, created lazily on first use.
- Support a key function; bonus: also accept a string property name.
- Preserve the original order of items within each group.
reducearrayobjectes2024
Important
Interview Tip
reduce with `(acc[k] ||= []).push(item)` is the cleanest one-liner. Mention that object keys are coerced to strings, and that ES2024 added native Object.groupBy and Map.groupBy (use Map.groupBy when you need non-string keys).
Approach: forEach + Object
Iterate, compute each key, and push into a lazily-created bucket. The clearest beginner-friendly answer.
Complexity
Time: O(n)Space: O(n)
Pros
- Very readable
- Easy to explain step by step
- Preserves item order
Cons
- A touch more verbose than reduce
- Key function only (no string shorthand)