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;
}
- Change
Record<string, T[]>toT[]type - Init the bucket:
(map[k] ??= []).push(item) - Change
oftoinin the for loop - Change
String(item[key])toitem[key]
The bucket array must exist before pushing into it.
Play Problem Solving ▸