Algorithmsmedium

Implement Dictionary `groupBy` utility

Given an array and a key selector, group items into a dictionary where each key maps to all matching items. Handle both function selectors and property-name selectors.

Asked at DriveNets

#groupBy#Map#array utilities

Answer

// Interview explanation:
// groupBy is O(n): scan once and bucket each item by computed key.
// Main edge cases interviewers expect:
// - selector is either a function or a property name
// - undefined/null keys are still grouped deterministically
// - stable order inside each group follows input order

function groupBy(items, selector) {
  const getKey =
    typeof selector === 'function'
      ? selector
      : (item) => item?.[selector]

  return items.reduce((acc, item) => {
    const key = String(getKey(item))
    if (!acc[key]) acc[key] = []
    acc[key].push(item)
    return acc
  }, {})
}

// Usage
const users = [
  { id: 1, team: 'A' },
  { id: 2, team: 'B' },
  { id: 3, team: 'A' },
]

groupBy(users, 'team')
// { A: [{id:1, team:'A'}, {id:3, team:'A'}], B: [{id:2, team:'B'}] }

groupBy(users, (u) => u.id % 2 === 0 ? 'even' : 'odd')
// { odd: [{id:1...}, {id:3...}], even: [{id:2...}] }

// Follow-up discussion:
// - Use Map instead of object when keys are not strings.
// - For large datasets, avoid JSON stringify key generation.
//
// Common interviewer follow-ups:
// Q: Complexity?
// A: Time is O(n) and extra space is O(n) in the worst case.
// Q: How to preserve insertion order of groups?
// A: Use Map for buckets; it preserves insertion order and supports non-string keys.
// Q: How to handle multi-key grouping?
// A: Apply nested grouping (group by key A, then group each bucket by key B).

Source: Glassdoor — DriveNets Front End Developer: https://www.glassdoor.com/Interview/DriveNets-Front-End-Developer-Interview-Questions-EI_IE2183997.0,9_KO10,29.htm

Practise more Algorithms questions →