JS Built-ins
ObjectObject.groupByintermediate

Object.groupBy() β€” group by property value

πŸ“– Usage Example
// Group array items by a computed key
const items = [{ type: 'a', v: 1 }, { type: 'b', v: 2 }, { type: 'a', v: 3 }]
Object.groupBy(items, item => item.type)
// β†’ { a: [{...}, {...}], b: [{...}] }

Use Object.groupBy() to group an array's elements into an object keyed by a value returned from a callback.

Object.groupBy() (ES2024)

Object.groupBy(array, keyFn) groups the elements of array into an object where the keys are the return values of keyFn.

Challenge: Implement groupByType(items) that groups objects in items by their type property.

groupByType([{type:'a',v:1},{type:'b',v:2},{type:'a',v:3}])
// β†’ { a: [{type:'a',v:1},{type:'a',v:3}], b: [{type:'b',v:2}] }
πŸ’‘ Hints (2)
  • β€’ `Object.groupBy(array, item => item.type)` groups by the `type` property.
  • β€’ Cast as `(Object as any).groupBy(...)` if TypeScript does not recognise it.