14. Implement groupBy(arr, key) — Group an Array

easy

A bread-and-butter reduce question. The only wrinkle is supporting both a property name and a key function — exactly what lodash.groupBy does.

The idea

Normalise key into a getKey function up front, then reduce into a plain object, creating each bucket on first use with ||=.

Follow-ups

  • "Object.groupBy exists now — why implement it?" → it's newer and not everywhere yet; the interviewer wants the mechanics.
  • "Preserve insertion order / non-string keys?" → return a Map instead of an object.
  • "Count instead of collect?" → swap the push for groups[k] = (groups[k] ?? 0) + 1.

What to practice

Write the array version, then a Map-returning variant that supports object keys.

More questions

index.js
function groupBy(arr, key) {
  // key can be a function or a property name
}

const people = [
  { name: 'Asha', city: 'Pune' },
  { name: 'Ravi', city: 'Pune' },
  { name: 'Mira', city: 'Delhi' },
];
console.log(groupBy(people, 'city'));

Tests

Test Code

Enter JavaScript that runs after your solution. It should return a value or a Promise.