Index by key in TypeScript
Indexes an array into a record keyed by one of its fields.
function keyBy<T, K extends string>(
items: T[],
keyFn: (item: T) => K,
): Record<K, T> {
const out = {} as Record<K, T>;
for (const item of items) {
out[keyFn(item)] = item;
}
return out;
}
Keywords and builtins used here
Tasconstextendsforfunctionofreturnstring
The run, in numbers
- Lines
- 10
- Characters to type
- 190
- Tokens
- 71
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 41 seconds.
Step 3 of 11 in Generic helpers, step 11 of 20 in Generics.