$ ./guess_the_languageProblem Solving — fix the bug
Problem Solving — fix the bug · hard · #50

What is the correct fix?

function groupBy<T>(arr: T[], key: keyof T) {
  const map: Record<string, T[]> = {};
  for (const item of arr) {
    const k = String(item[key]);
    map[k].push(item);
  }
  return map;
}
  1. Change Record<string, T[]> to T[] type
  2. Init the bucket: (map[k] ??= []).push(item)
  3. Change of to in in the for loop
  4. Change String(item[key]) to item[key]
The bucket array must exist before pushing into it.
Play Problem Solving ▸