0 of 5 problems solved0%
5 of 5

Index by Key

Build a dictionary from an array using a key selector. Constrain the key’s type with K extends PropertyKey so it can be used as an object key (string | number | symbol). Return a Record<K, T> so callers get precise value types.

When two items produce the same key, let the later one win. Keep the function pure by creating a new object.

function byId<T>(items: T[], getId: (t: T) => string) {
  /* ... */
}

Your Task

Create a map from keys to items.

  • Implement function indexBy<T, K extends PropertyKey>(items: T[], key: (item: T) => K): Record<K, T>.
  • Insert each item under its selected key; if a key repeats, overwrite the previous item.
  • Do not mutate the input array; return a new plain object.
  • Return an empty object for an empty input.