A bread-and-butter reduce question. The only wrinkle is supporting both a property name and a key function — exactly what lodash.groupBy does.
Normalise key into a getKey function up front, then reduce into a plain object, creating each bucket on first use with ||=.
Object.groupBy exists now — why implement it?" → it's newer and not everywhere yet; the interviewer wants the mechanics.Map instead of an object.groups[k] = (groups[k] ?? 0) + 1.Write the array version, then a Map-returning variant that supports object keys.
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'));
Test Code
Enter JavaScript that runs after your solution. It should return a value or a Promise.