JS Built-ins
ObjectObject.groupByintermediate

Object.groupBy() β€” group strings by length

πŸ“– 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() β€” numeric group keys

The key function can return a number too (it gets coerced to a string key). Grouping strings by length is a common example.

Challenge: Implement groupByLength(words) that groups strings by their .length.

groupByLength(['a', 'bb', 'cc', 'ddd'])
// β†’ { '1': ['a'], '2': ['bb', 'cc'], '3': ['ddd'] }
πŸ’‘ Hints (1)
  • β€’ Return `w.length` from the key function β€” numbers are coerced to string keys.