Skip to content

2631. Group By 👍

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
declare global {
  interface Array<T> {
    groupBy(fn: (item: T) => string): Record<string, T[]>;
  }
}

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