EasyJavaScriptTypeScript

Utility Types — Record<K, V>

TypeScriptUtility TypesRecords

Record<K, V> creates an object type with keys of type K and values of type V.

Implement two functions:

1. `groupBy<T>(items: T[], key: keyof T): Record<string, T[]>`
Groups items by the value of key.

2. `invertRecord(rec: Record<string, string>): Record<string, string>`
Swaps keys and values.

Examples

  • groupBy([{lang:'js'},{lang:'ts'},{lang:'js'}], 'lang'){ js: [{lang:'js'},{lang:'js'}], ts: [{lang:'ts'}] }
  • invertRecord({ a: '1', b: '2' }){ '1': 'a', '2': 'b' }

Sample tests

Test #1groupBy — by lang
Input: ["groupBy",[{"lang":"js"},{"lang":"ts"},{"lang":"js"}],"lang"]
Output: {"js":[{"lang":"js"},{"lang":"js"}],"ts":[{"lang":"ts"}]}
Test #2invertRecord — basic
Input: ["invertRecord",{"a":"1","b":"2"}]
Output: {"1":"a","2":"b"}
Test #3groupBy — empty array
Input: ["groupBy",[],"x"]
Output: {}