Skip to main content
Back to problems
#2631
Medium JavaScript

Group by

81.3% acceptance
Mar 2, 2026
366
21
Write code that enhances all arrays such that you can call the array.groupBy(fn) method on any array and it will return a grouped version of the array. A grouped array is an object where each key is the output of fn(arr[i]) and each value is an array containing all items in the original array which generate that key. The provided callback fn will accept an item in the array and return a string key. The order of each value list should be the order the items appear in the array. Any order of keys is acceptable. Please solve it without lodash's _.groupBy function.

Solution

TypeScript
Time O(n)
Space O(1)
LeetCode
solution.ts
interface Array<T> {
  groupBy(fn: (item: T) => string): Record<string, T[]>;
}

Array.prototype.groupBy = function <T>(
  fn: (item: T) => string,
): Record<string, T[]> {
  const result: Record<string, T[]> = {};
  for (const item of this) {
  const key = fn(item);
  if (!result[key]) result[key] = [];
  result[key].push(item);
  }
  return result;
};